RangeError: Maximum call stack size exceeded [Steamroller]

I’m working on a problem is known as Steamroller.
Here is my code to fix this,

function steamrollArray(arr) {
  arr = arr.reduce((acc, val) => acc.concat(val), []);
  var result = [];
  for(let i=0; i<arr.length; i++){
    result.push(typeof(arr[i]));
  }
  for(let i=0; i<result.length; i++){
    if(result[i] === "object"){
      arr = steamrollArray(arr);
    }
  }
  return arr;
}

One of the test cases didn’t pass. It was - steamrollArray([1, {}, [3, [[4]]]]) should return [1, {}, 3, 4]

It’s showing an error - RangeError: Maximum call stack size exceeded
But I don’t understand what is stack or stack size that exceeded?
Can you please explain what’s going on with my code :roll_eyes:

You’ve set up an infinite recursion here.

The ‘call stack’ is a sort of ToDo list of the function calls your computer needs to complete. With an infinite recursion, this stack keeps getting bigger and bigger until JavaScript crashes.

1 Like

After all the list of Arr turns to string or number, there will be no object left in Arr. Why it’s infinite?

This isn’t happening though. You are just copying the array.


Three pieces of advice

  • Don’t try to replace arr, build a new array with the ‘unrolled’ contents

  • You only need one loop (and a reduce is a type of loop, in a sense)

  • Recursion needs a reduced input to terminate. What about unrolling entries of arr?

1 Like

Is that a good fix? :grimacing:

function steamrollArray(arr) {
  for(let i=0; i<arr.length; i++){
    arr = arr.reduce((acc, val) => acc.concat(val), []);
  }
  return arr;
}

Unfortunately, this solution works by luck with the test suite and won’t work for every single test case.

console.log(steamrollArray([1, [[[[[2]]]]], [3, [[4]]]]))
1 Like