Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS: Switch case seemingly goes to default

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:

why

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading