Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

84
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda