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']));
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Conrade
  • 3
  • 2
  • Please include a [mre], with enough code that we can reproduce the situation. – Heretic Monkey Aug 18 '22 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? – Andrew Morton Aug 18 '22 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. – Heretic Monkey Aug 18 '22 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. – Chuck Aug 18 '22 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. – Conrade Aug 18 '22 at 18:22
  • Ahh I see, if you take more limes than there are entries in the limes array, then you get `undefined`, which DOES trip the default case, then the next attempt also gets `undefined`, etc. Should be a check in there to see if there are any limes remaining before getting a lime. – Chuck Aug 18 '22 at 18:22
  • Works with the data I added to a Stack Snippet (in an effort to create a [mre]). Please enter the data you are using that produces an infinite loop. – Heretic Monkey Aug 18 '22 at 18:27

1 Answers1

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!

realSamy
  • 189
  • 6