In javascript, I want to at least consider using a nested object literal tree for my control flow instead of if statements, switch statements, etc.
Below is an example of a function using if statements turned into a function using object literals to acplish the same functionality.
// if & else if
function getDrink (type) {
if (type === 'coke') {
type = 'Coke';
} else if (type === 'pepsi') {
type = 'Pepsi';
} else if (type === 'mountain dew') {
type = 'Mountain Dew';
} else {
// acts as our "default"
type = 'Unknown drink!';
}
return type;
}
// object literal
function getDrink (type) {
var drinks = {
'coke': function () {
return 'Coke';
},
'pepsi': function () {
return 'Pepsi';
},
'Mountain Dew': function () {
return 'Mountain dew';
},
'default': function () {
return 'Unknown drink!';
}
};
return (drinks[type] || drinks['default'])();
}
In javascript, I want to at least consider using a nested object literal tree for my control flow instead of if statements, switch statements, etc.
Below is an example of a function using if statements turned into a function using object literals to acplish the same functionality.
// if & else if
function getDrink (type) {
if (type === 'coke') {
type = 'Coke';
} else if (type === 'pepsi') {
type = 'Pepsi';
} else if (type === 'mountain dew') {
type = 'Mountain Dew';
} else {
// acts as our "default"
type = 'Unknown drink!';
}
return type;
}
// object literal
function getDrink (type) {
var drinks = {
'coke': function () {
return 'Coke';
},
'pepsi': function () {
return 'Pepsi';
},
'Mountain Dew': function () {
return 'Mountain dew';
},
'default': function () {
return 'Unknown drink!';
}
};
return (drinks[type] || drinks['default'])();
}
This works when testing for a simple value, but how could I turn the following switch statement into an object literal control structure?
switch (true) {
case (amount >= 7500 && amount < 10000):
//code
break;
case (amount >= 10000 && amount < 15000):
//code
break;
//etc...
Share
Improve this question
asked Jun 12, 2018 at 12:27
GallaxharGallaxhar
1,0361 gold badge17 silver badges30 bronze badges
6
- 1 You can't have an expression as an object key and I don't see anything wrong with a case or ifs for conditions? Also if your example is as simple as you've demonstrated you don't need to assign a function for every key, a value string would do. – nanobar Commented Jun 12, 2018 at 12:37
- Object keys can be expressions xahlee.info/js/js_object_literal_expression.html – Gallaxhar Commented Jun 12, 2018 at 12:43
- Of course you can do your own putation on a string but it's totally overkill and slower to do so for a stylistic opinion – nanobar Commented Jun 12, 2018 at 12:46
- The goal is to make it look similar to this fiddle, but can't get it working. It's much easier to read. My app does not care about speed. jsfiddle/9txnegvh/11 – Gallaxhar Commented Jun 12, 2018 at 12:47
- jsfiddle/9txnegvh/14 works – Gallaxhar Commented Jun 12, 2018 at 12:50
3 Answers
Reset to default 3A small helper usong Array.find might be useful:
const firstCase = (...cases) => value => cases.find(c=> c[0](value))[1];
Which is usable as:
const dayTime = firstCase(
[t => t < 5, "night"],
[t => t < 12, "morning"],
[t => t < 18, "evening"],
[true, "night"]
);
console.log(dayTime(10)); // morning
That also works with functions:
const greetAtTime = firstCase(
[t => t < 10, name => `Good morning ${name}!`],
[t => t > 18, name => `Good evening ${name}!`],
[true, name => `Hello ${name}!`]
);
console.log(greetAtTime(12)("Jack"));
You can use the simple way
const handlerPayment = () => { };
const handlerFailure = () => { };
const handlerPending = () => { };
// Switch
switch (status) {
case 'success':
return handlerPayment();
case 'failed':
return handlerFailure();
case 'pending':
return handlerPending();
default:
throw Error('Status not recognize');
}
// Object
const Handlers = {
success: handlerPayment,
failed: handlerFailure,
pending: handlerPending,
}
const handler = Handlers[status];
if (!handler) throw Error('Status not recognize');
return handler();
This appears to work
const getValue = (value) => ({
[value == 1]: 'Value is 1',
[value > 1]: 'Value is greater than 1',
[value < 1]: 'Value is less than 1',
})[true]
console.log(getValue(2));
console.log(getValue(-1));
console.log(getValue(-1+2)); // expect 'Value is 1'