Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List manipulation leads to infinite loop

I am trying to create an array for listing purposes in Ionic Framework and check all the callcenter name's first char to add them in an alphabet array.

  for (var i = 0; i < callcenterList.length; i++) {
    var value = callcenterList[i]._owner && callcenterList[i]._owner.company.name[0];

    if ((alphabet.indexOf(value) == -1 && isNaN(parseInt(value))) ||
      (isNaN(alphabet[0]) && !isNaN(value))) {
      if(!isNaN(value))
        value = 123;

      alphabet.push(value);

      callcenterList.splice(i, 0, {
        divider: {
          alphabet: value
        }
      });
    }
  };

Replacing value = 123 with value = '#' causes Google Chrome and Google Chrome Canary to malfunction and immediately use up to 100% of RAM in Mac.

Is this a Javascript bug or is it related to Google Chrome itself?

like image 637
Yagiz Avatar asked Feb 18 '16 21:02

Yagiz


1 Answers

This isn't a bug in your browser or anything: you're just creating a condition where your code goes into an infinite loop, which always tends to make the browser seize up. You can do the same thing with a simple while (true) {} loop.

Specifically, you are iterating over the callcenterList, and any time isNaN(alphabet[0]), you are splicing a new element into callcenterList. alphabet[0] is going to have the first value that you push there which, in the conditional you're looking at, you're going to set to '#'.

Therefore, isNaN(alphabet[0]) will always be true.

Therefore, you'll continue to add values into callcenterList.

Therefore i < callcenterList.length will always be true.

like image 52
StriplingWarrior Avatar answered Sep 21 '22 22:09

StriplingWarrior