Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

85
Views
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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!