I'm having an issue with this code I'm writing for a challenge.
The code I wrote goes in an infinite loop and I can't understand what's wrong.
var wiggleMaxLength = function(nums) {
let wiggleSteps = 1;
let actualDiff, pastDiff, i;
for (i = 1; i < nums.length; i++) {
actualDiff = (nums[i] - nums[i - 1])
if (nums[i] = 0) {
nums.splice(i, 1);
i--;
continue;
} else if ((pastDiff > 0 && actualDiff < 0) || (pastDiff < 0 && actualDiff > 0) || (i = 1)) {
pastDiff = actualDiff;
wiggleSteps++;
} else {
break;
}
}
return wiggleSteps;
};
There is a typo on line 6 (= instead of == or ===)
if (nums[i] = 0)
I assume that you didn't see it.
This assigns the value 0 to nums[i], instead of comparing nums[i] to 0.
Therefore, you should change the if into
if (nums[i] == 0)
or
if (nums[i] === 0)
Note that there is also an additional typo on line 9 in the 3rd condition i = 1 instead of i == 1 or i === 1, which is the reason that causes the infinite loop (as the counter 'i' is always re-assigned to 1).
The program always goes on the else if branch.