Potential Infinite Loop

Potential Infinite Loop
0

#1

Hi - can someone please explain why I’m getting a warning for a potential infinite loop for line 13 of my code below? (line starting with “finalArr.splice”). I would think the “i<arr.length” condition in the for loop would prevent this from being infinite? I added the finalArr variable so that the length of arr would remain fixed even as I’m adding additional elements into my array, but that didn’t seem to fix it. I’m going to go a different direction with this challenge (DNA Pairing) in any event, but I’ve had this same message/problem in a few challenges so I’m clearly not understanding something really basic!

function pairElement(str) {
  var arr = str.split("");
  var finalArr = arr;
  var pairs = {
    "G" : "C",
    "C" : "G",
    "A" : "T",
    "T" : "A"
  };
  
// for each element in the array, add its pair into the array at the index immediately after it
  for (var i=0; i<arr.length; i++) {
     finalArr.splice(arr[i+1], 0, pairs[arr[i]]); 
  } 

//next separate finalArr into separate arrays by 2

  return finalArr;
}


#2

One thing to note that may be causing your problem - your “finalArr” variable points to the same underlying array as “arr” since JS passes objects by reference not value. You can use slice() to return a copy instead of that is what you are going for.


#3

Thanks for the tip re: slice. I’ll definitely give that a try.