Increment MarvinLabs answer to make it cleaner:
var x = this.dealer; switch (true) { case (x < 5): alert("less than five"); break; case (x < 9): alert("between 5 and 8"); break; case (x < 12): alert("between 9 and 11"); break; default: alert("none"); break; }
There is no need to check the lower limit of the range, because break statements will force execution to skip the remaining cases, so by the time execution is checked, for example. (x <9), we know that the value must be 5 or more.
Of course, the result is correct if the cases remain in the original order, and we accept integer values ββ(as indicated in the question) - technically, the ranges are between 5 and 8.999999999999 or so, since all numbers in js actually double-digit floating-point numbers.
If you want to be able to move cases around or find them more readable so that the entire range is displayed in each case, just add a less or equal check for a lower range for each case:
var x = this.dealer; switch (true) { case (x < 5): alert("less than five"); break; case (x >= 5 && x < 9): alert("between 5 and 8"); break; case (x >= 9 && x < 12): alert("between 9 and 11"); break; default: alert("none"); break; }
Keep in mind that this adds an additional point of human error - someone may try to update the range, but forget to change it in both places, leaving an overlap or a space that does not cover. for example, here case 8 will no longer match anything when I just edit the case that was used to match 8.
case (x >= 5 && x < 8): alert("between 5 and 7"); break; case (x >= 9 && x < 12): alert("between 9 and 11"); break;
David Mason 09 Oct '13 at 23:44 2013-10-09 23:44
source share