Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

79
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda