What is the best practices to handle multiple condition cases if they are not bound to one variable?
For Example we could use else if
statement:
if (a && b > 10) {
...
} else if (a && b < 5) {
...
} else if (!a && c === 'test') {
....
} else if (!a && c === 'test2') {
...
} else {
...
}
That is just example, so don't try to simplify it by regrouping logic. Notice that we can't use simple switch here. We can't use map with options either.
As an alternative we can use switch(true)
to make it more readable:
switch(true) {
case (a && b > 10):
...
break;
case (a && b < 5):
...
break;
case (!a && c === 'test'):
...
break;
case (!a && c === 'test2'):
...
break;
default:
...
}
It is absolutely legal and recommended by many authors. But from the other hand many developers don't like it as true statement is not a variable but constant.
I've read a few posts about switch(true)
usage. Like following: javascript switch(true)
What would be the best solutions for such multiple conditions without one single variable?
Solution: I end up with simplified version of Erik Philips answer. Thank you Erik!
let descriptionByType: {description: string, check: check: () => Boolean}[] = [
{ description: 'result 1', check: () => a && b > 10 },
{ description: 'result 2', check: () => a && b < 5 },
{ description: 'result 3', check: () => !a && c === 'test' },
{ description: 'result 4', check: () => !a && c === 'test2' },
{ description: 'default result', check: () => true },
];
return descriptionByType.find(x => x.check()).description;
It is quite clear and flexible.