P粉6800875502023-08-19 00:33:06
You can make your logic more data-driven by using objects, for example:
var outcomeMap = { active: { active: "a", locked: "b", disabled: "c" }, inactive: { active: "d", locked: "e", disabled: "f", } };
You can then set your outcome
variable by accessing that object using a
and accessing the value of the nested object, for example:
var outcome = outcomeMap[a][b];
Please note that if a
can be any other value than the one you mentioned, it is better to check outcomeMap[a]
before accessing b
Whether it is undefined
. This can be done using optional chaining if your environment supports it, for example: outcomeMap[a]?.[b];
Alternatively, you can set up an array containing the possible combinations and then loop through them to check if your combination matches. Then, based on the current index, if a result is found, you can index to your result (outcomes
), for example:
function getOutcome(a, b) { const aVals = ['active', 'inactive']; const bVals = ['active', 'locked', 'disabled']; const outcomes = [['a', 'b', 'c'], ['d', 'e', 'f']]; for(const [i, aVal] of aVals.entries()) { for(const [j, bVal] of bVals.entries()) { if (aVal == a && bVal == b) { return outcomes[i][j]; } } } // return ''; if you want a default value of empty string } const outcome = getOutcome('inactive','locked'); console.log(outcome);
Please note that neither method is more efficient than using an if statement. However, if you have more possibilities, they should be easier to scale.