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 {
...
}
Notice that we can't use simple switch here. We can't use map with options either. But 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:
...
}
Or like that:
switch(true) {
case isValid():
...
break;
case hasMeasurements():
...
break;
case isHighDensity():
...
break;
case isObsolete():
...
break;
default:
...
}
I've read a few posts about switch(true)
usage. Like following: javascript switch(true)
Some people say that there is nothing wrong in that. Others suggest not to use it at all.
What would be the best solutions for such multiple conditions without one single variable?
Aucun commentaire:
Enregistrer un commentaire