const computeDash=(num)=>{
const arr=num.split('');
const nums=arr.map(Number);
for(let i=0;i<(nums.length-1);i ){
if(nums[i]%2===0 && nums[i 1]%2===0){
nums.splice(i,0,'-');
}
}
return nums.join('');
}
console.log(computeDash('025468'));
The above code is giving FATAL ERROR.
But the below code is working fine when I changed for loop. I can't understand why 1st code giving error. Does anyone know why?
const computeDash=(num)=>{
const arr=num.split('');
const nums=arr.map(Number);
for(let i=0;i<nums.length;i ){
if(nums[i-1]%2===0 && nums[i]%2===0){
nums.splice(i,0,'-');
}
}
return nums.join('');
}
console.log(computeDash('025468')); //0-254-6-8
CodePudding user response:
In general I don't recommend altering an array while you are looping through it. Your for loop will not be reliable in terms of the count of nums
because the length of the array is changing while you are looping. In this case the fatal error occurs because you are getting into an infinite loop due to the fact that nums.length
keeps increasing every time you insert a new -
into the array.
As to the specific question, why does one work and not the other - mainly its about luck here. Other inputs would behave differently. But the program as written should be considered suspicious in both cases!
Here is an example of looping without altering the array you are looping ... instead we push the numbers to a new array which will contain the desired result.
const computeDash = (num) => {
const arr = num.split('');
const nums = arr.map(Number);
const result = [];
for (let i = 0; i < (nums.length-1); i ) {
result.push(nums[i]);
if (nums[i] % 2 === 0 && nums[i 1] % 2 === 0) {
result.push('-');
}
}
result.push(nums[nums.length-1]);
return result.join('');
}
console.log(computeDash('025468'));
CodePudding user response:
The first approach is not working because you are adding the '-' at index i. And for the given test case '025468' your loop keeps on adding '-' at the start always. i.e. after the first iteration, the array would be ['-',0,2,5,4,6,8] and after the second iteration it becomes ['-','-',0,2,5,4,6,8] and goes in an infinite loop.
The fix that will make the first approach work is
const computeDash=(num)=>{
const arr=num.split('');
const nums=arr.map(Number);
for(let i=0;i<(nums.length-1);i ){
if(nums[i]%2===0 && nums[i 1]%2===0){
nums.splice(i 1,0,'-');
}
}
return nums.join('');
}
console.log(computeDash('025468'));