0

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']));

7
  • Please include a minimal reproducible example, with enough code that we can reproduce the situation. Commented Aug 18, 2022 at 18:18
  • 1
    Are you sure that lime has any of the values in the switch? If you put an alert in the default case, does that appear? Commented Aug 18, 2022 at 18:18
  • Note that if limes contains none of those strings, it will loop indefinitely. Also, if limes does not contain enough of those string to get wedgesNeeded down to 0, it will continue to loop. Commented Aug 18, 2022 at 18:19
  • @HereticMonkey - I thought the same at first, but if it's default doesn't it move to the next lime? let lime = limes.shift(); it only gets evaluated once, right? I have no idea why this would loop infinitely; I'd think you'd eventually run out of limes. Commented Aug 18, 2022 at 18:20
  • @AndrewMorton yeah the values are correct. If I console.log(${wedgesNeeded} ${total}) after the switch it will return all the correct values. The total increases correctly and the wedgesNeeded will decrease correctly. Commented Aug 18, 2022 at 18:22

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

4 Comments

This works, thank you. Is there a way to remove the if statement and include another condition in the whileloop instead?
@Conrade sure, done!
Legend, mate. What does the '!!' mean?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.