Javascript Array.reduce() breaking the page with Error Code 6

392 Views Asked by At

The webpage works fine as long as I don't pass an initial value, but in that case it just gives me the TypeError because when there's only the last element (as expected). Which is why I am trying to pass 0 as the initial value to the reduce function (line 4 of below snippet). But as soon as I do that, it just breaks the entire page with an error code 6.

What I'm trying to achieve: I'm adding the sum of all the elements of the array, then pushing that sum to another array, removing the first element and repeating the process. When there are no elements left, I want to return 0 from the reduce() function which is why I'm trying to pass an initial value (0).

function partsSums(ls) {
  let sumArr = [];
  while (ls.length >= 0) {
    sumArr.push(ls.reduce((acc, cur) => acc + cur, 0));
    ls.shift();
  }
  return sumArr;
}

partsSums([0, 1, 3, 6, 10]);

The output I'm looking for is: [20, 20, 19, 16, 10, 0]

Error Screenshot

3

There are 3 best solutions below

1
On BEST ANSWER

you can do that:

function partsSums(ls)
  {
  let sumArr = []
    , lng    = ls.length
    ;
  while ( lng >= 0)
    {
    sumArr.push(ls.reduce((acc, cur) => acc + cur, 0))
    ls.shift()
    --lng
    }
  return sumArr
  }

console.log(JSON.stringify( partsSums([0, 1, 3, 6, 10])  ))
.as-console-wrapper { max-height: 100% !important; top: 0; }

0
On

As mentioned in the comments, you're getting an infinite loop because the length of the array will never go below 0.

As shown in other answers, you can solve that by changing the condition to ls.length > 0, but then you won't get the end case of pushing 0 into the result in the final iteration when the array is empty.

Instead of testing the length in the while() condition, test it after you call reduce() and then break out of the loop.

function partsSums(ls) {
  let sumArr = [];
  while (true) {
    sumArr.push(ls.reduce((acc, cur) => acc + cur, 0));
    if (ls.length == 0) {
      break;
    }
    ls.shift();
  }
  return sumArr;
}

console.log(partsSums([0, 1, 3, 6, 10]));

4
On

The problem with your code is the condition ls.length >= 0. This condition leads you to an infinite loop. Change it to ls.length > 0

Suggestion

It seems you are seeking a cumulative summation from right to left. But your function is not cost-effective. You can use suffix-sum for this problem.

const suffixSum = arr => {
  const res = [];
  const {length} = arr;
  res[length] = 0;

  for (let i = length - 1; i >= 0; i--) {
    res[i] = res[i+1] + arr[i];
  }
  
  return res;
}

console.log(suffixSum([0, 1, 3, 6, 10]));

This algorithm takes O(n) time while your algorithm takes O(n^2) time.