Switch cases are usually like
Monday:
Tuesday:
Wednesday:
etc.
I would like to use ranges.
from 1-12:
from 13-19:
fr
you could try abusing the switch fall through behaviour
var x = 5;
switch (x) {
case 1: case 2: case 3: case 4: ...
break;
case 13: case 14: case 15: ...
break;
...
}
which is very verbose
or you could try this
function checkRange(x, n, m) {
if (x >= n && x <= m) { return x; }
else { return !x; }
}
var x = 5;
switch (x) {
case checkRange(x, 1, 12):
//do something
break;
case checkRange(x, 13, 19):
...
}
this gets you the behaviour you would like. The reason i return !x
in the else of checkRange is to prevent the problem of when you pass undefined
into the switch statement. if your function returns undefined
(as jdk's example does) and you pass undefined
into the switch, then the first case will be executed. !x
is guaranteed to not equal x
under any test of equality, which is how the switch statement chooses which case to execute.