I have two variables like below:
var a = "active" //[two possible value active/inactive]
var b = "inactive" //[three possible values active/locked/disabled]
var outcome = ""
if(a=="active" && b=="active")
outcome = "a";
elif(a=="active" && b=="locked")
outcome = "b"
elif(a=="active" && b=="disabled")
outcome = "c"
elif(a=="inactive" && b=="active")
outcome = "d"
elif(a=="inactive" && b=="disabled")
outcome = "e"
elif(a=="inactive" && b=="locked")
outcome = "f"
What is the most efficient way of describing the possible outcomes other than using ifelse checking for different conditions in JS?Please suggest.
3
Answers
You could make your logic more data-driven by using an object, for example:
You can then set your
outcome
variable by accessing this object usinga
, and then accessing the nested object’s value, for example:Note that if
a
can be anything other than the values you have mentioned, it’s best to check thatoutcomeMap[a]
isn’tundefined
before accessingb
. If your environment supports it, that can be done using optional chainingoutcomeMap[a]?.[b];
Alternatively, you could set up arrays with your possible combinations, and then loop through them to check if your combinations match. You can then index into your results (
outcomes
), based on your current index if you find a result, for example:Note that neither of these approaches are more efficient than using an if-statement. However, they should be easier to scale if you get more possiblilities.
A simple way would be to simply add the string values of a and b and then define the possible outcomes in an object. For simplicity, I have not included all options in your example:
Then you can simply get your outcome with:
Although, if else statements are quite fast in JavaScript, this might be an option if you have many elif statements.
If your variables have finite number of possible values, I would first suggest using enums to store those and make code more readable:
You could then use string concatenation to transform your elseifs to a switch case: