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.
>Solution :
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)))
