Skip to content
Advertisement

My while loop in JavaScript gets stuck in an infinite loop when the subtractive condition is included

I’m doing this exercise where you have to calculate the number of limes needed to get the juice. It needs a switch statement inside which takes out the first element of the “limes” array, (and that works flawlessly). Until i add the condition to count down the wedges: even if in the cases is specified to subtract a determined amount, at every iteration it seems to ignore it and never meeting the needed condition to break the switch statement

here’s the code

function limesToCut(wedgesNeeded, limes) {
    let limesNeeded = 0
    while(limes.length != 0 || wedgesNeeded > 0 ) {    
        switch (limes[0]) {          
            case 'small':       
                limes.shift() 
                limesNeeded += 1
                wedgesNeeded -= 6
                break;
            case 'medium': 
                limes.shift()
                limesNeeded += 1
                wedgesNeeded -= 8
                break;
            case 'large': 
                limes.shift()
                limesNeeded += 1
                wedgesNeeded -= 10
                break;
            default:
                break  
        } 
    }
    console.log(limesNeeded)
}

//test cases

console.log("case 1")
limesToCut(4, ['medium', 'small'])
console.log("case 2")
limesToCut(80,['small','large','large','medium','small','large','large',])
console.log("case 3")
limesToCut(0, ['small', 'large', 'medium'])
console.log("case 4")
limesToCut(10, [])

where did i go wrong? it seems to not be working even when i exclude the other condition from the loop

Advertisement

Answer

quoting @James in the comments: It’s because for some of your test cases, limes.length != 0 || wedgesNeeded > 0 is always true, so it gets stuck in a loop. Consider the case where you need 80 wedges but only have 7 limes which could yield 70 wedges tops (if they were all the largest size). So there are no limes left but wedgesNeeded > 0, so it loops and loops.

Advertisement