views:

268

answers:

5

Switch cases are usually like

Monday: 
Tuesday: 
Wednesday: 
etc.

I would like to use ranges.

from 1-12: 
from 13-19:
from 20-21:
from 22-30:

Is it possible? I'm using javascript/jquery by the way.

A: 

I think in IF statement would be better here...

clownbaby
A: 

Nope, you need to use an if/else if series to do this. JavaScript isn't this fancy. (Not many languages are.)

John Kugelman
+3  A: 

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.

barkmadley
+1  A: 

You can make interesting kludges. For example, to test a number against a range using a JavaScript switch, a custom function can be written. Basically have the function test a give n value and return it if it's in range. Otherwise returned undefined or some other dummy value.

<script>

// Custom Checking Function..
function inRangeInclusive(start, end, value) {
    if (value <= end && value >= start)
     return value; // return given value
    return undefined; 
}

// CODE TO TEST FUNCTION
var num = 3;
switch(num) {
case undefined:
    //do something with this 'special' value returned by the inRangeInclusive(..) fn
    break;
case inRangeInclusive(1, 10, num):
    alert('in range');
    break;
default:
    alert('not in range');
    break;
}

</script>

This works in Google Chrome. I didn't test other browsers.

John K
does it work if num is undefined?
barkmadley
It doesn't work as expected if num is undefined.
John K
@barkmadley: I just edited the code and added a case for the undefined value to explicitly handle it. There might be a better return value to use in the inRangeInclusive(..) function. Open to suggestions. Thanks.
John K
check my solution, `!value` works perfectly
barkmadley
A: 
stephennmcdonald