I have a very simple method that receives a number and returns a text based on the range. This is it:
getBoardLocation(num) {
switch (num) {
case (6 >= num >= 1):
return 'bl';
case (12 >= num >= 7):
return 'br';
case (18 >= num >= 13):
return 'tl'
case (24 >= num >= 19):
return 'tr';
default:
break;
}
}
For some reason, despite being sure via breakpoints that the parameter being passed is indeed a number, and indeed in the range of one of the cases, it just goes to the default case, as seen in devtools, like here:
I feel like I missed something incredibly stupid, but I can't figure out what.
CodePudding user response:
there are many things wrong with your switch
try this
const isBetween = (n, start, stop) => n >= start && n <= stop
function getBoardLocation (num) {
switch (true) {
case isBetween(num, 1, 6):
return 'bl';
case isBetween(num, 7, 12):
return 'br';
case isBetween(num, 13, 18):
return 'tl'
case isBetween(num, 19, 24):
return 'tr';
default:
throw new Error(num 'is not valid')
}
}
[1, 9, 14, 21].forEach(n => console.log(n, getBoardLocation(n)))
another approach could be this using some sort of a configuration object
const config = [
{min: 1, max: 6, value: 'bl'},
{min: 7, max: 12, value: 'br'},
{min: 13, max: 18, value: 'tl'},
{min: 19, max: 24, value: 'tr'}
]
function getBoardLocation (num) {
const res = config.find(({min, max}) => num >= min && num <= max)?.value
if(!res){
throw new Error(num 'is not valid')
}
return res
}
[1, 9, 14, 21].forEach(n => console.log(n, getBoardLocation(n)))
CodePudding user response:
You'll be disappointed to learn that JS switch statements don't work the way you think.
The value provided in the case
statment must exactly match the value provided in the switch
statement for that specific case to match.
In your case, true
/false
doesn't ever match the provided number, so you fall through to the default case.
CodePudding user response:
from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch:
The switch statement evaluates an expression, matching the expression's value against a series of case clauses, and executes statements after the first case clause with a matching value, until a break statement is encountered. The default clause of a switch statement will be jumped to if no case matches the expression's value.
which means the expression (num
) is evaluated to 1 in your example,
but the expressions in the cases are evaluated to either true
/false
, and 1 !== true