3

Is there a way in Javascript to compare one integer with another through switch case structures without using if statements?

E.g.

switch(integer) {
    case 1 to 10:
        break;
    case 11 to 20:
        break;
    case 21 to 30:
        break;
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Tommy Plummer
  • 351
  • 2
  • 5
  • 14
  • No. Well, you could have `switch(integer < 10) { case true:....}` (which is comparing an integer with another through `switch`) but I guess that's not helpful. – Felix Kling Dec 16 '11 at 01:42
  • Ah ok. I asked because it would seem a lot easier to read and code than if(integer<= 10) and so forth. I've seen the syntax somewhere before, but I forget where and what for. – Tommy Plummer Dec 16 '11 at 01:46

4 Answers4

6

You can do some math manipulations.

switch(Math.ceil(integer/10)) {
    case 1: // Integer is between 1-10
        break;
    case 2: // Integer is between 11-20
        break;
    case 3: // Integer is between 21-30
        break;
}
Skyd
  • 411
  • 4
  • 11
4

There is a way, yes. I'm pretty sure I'd use an if/else structure in my own code, but if you're keen to use a switch the following will work:

switch(true) {
   case integer >= 1 && integer <= 10:
      // 1-10
      break;
   case integer >= 11 && integer <= 20: 
      // 11-20
      break;
   case integer >= 21 && integer <= 30:
      // 21-30
      break;
}

Of course if you wanted to avoid having to code >= && <= on every case you could define your own isInRange(num,min,max) type function to return a boolean and then say:

switch (true) {
   case isInRange(integer,1,10):
      // 1-10
      break;
   // etc
}
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
3

As stated in my comment, you can't do that. However, you could define an inRange function:

function inRange(x, min, max) {
    return min <= x && x <= max;
}

and use it together with if - else if. That should make it quite easy to read:

if(inRange(integer, 1, 10)) {

}
else if(inRange(integer, 11, 20)) {

}

//...
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

Posting for "cool" syntax :P

if( integer in range(0, 10 ) ) {

}
else if ( integer in range( 11, 20 ) ) {



}
else if ( integer in range( 21, 30 ) ) {



}

function range( min, max ){
var o = {}, i ;
    for( i = min; i <= max; ++i ) {
    o[i] = !0;
    }
return o;
}
Esailija
  • 138,174
  • 23
  • 272
  • 326