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

Why does my while loop condition not end the loop?

I am confused as to why my function continues to loop. wedgesNeeded = number, limes = array

function limesToCut(wedgesNeeded, limes) {
  let total = 0
  while (wedgesNeeded > 0) {
    let lime = limes.shift()
    switch (lime) {
      case 'small':
        wedgesNeeded -= 6;
        total++;
        break;
      case 'medium':
        wedgesNeeded -= 8;
        total++;
        break;
      default:
    }
  }
  return total
}
console.log(limesToCut(12, ['small','small']));

>Solution :

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

Your situation occurs when the wedgesNeeded is much bigger than what you expect; Your loop will empty the limes array but wedgesNeeded is still bigger than 0

function limesToCut(wedgesNeeded, limes) {
  let total = 0
  while (wedgesNeeded > 0 && !!limes.length) {
    let lime = limes.shift()
        switch (lime) {
          case 'small':
            wedgesNeeded -= 6;
            total++;
            break;
          case 'medium':  
            wedgesNeeded -= 8;
            total++;
            break;
          default:
        }
    }
  return total
}

count = limesToCut(200000, ['small', 'medium', 'small', 'medium', 'small', 'medium'])
console.log(count)

Edit: Replaced the if condition by while condition!

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