问题
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 accomplish 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...
回答1:
A 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"));
回答2:
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'
来源:https://stackoverflow.com/questions/50817227/javascript-how-to-use-object-literals-instead-of-if-and-switch-statements-for-e