3

I have attempted to add min() and max() functions to arrays, implemented using the ... operator:

Array.prototype.min = Array.prototype.min || function () {
    return Math.min(...this);
};

However, when calling these functions on large arrays, I get an exception: "RangeError: Maximum call stack size exceeded". What is going on?

console.log(new Array(100000).min());  /* works */
console.log(new Array(1000000).min()); /* error */
kfx
  • 8,136
  • 3
  • 28
  • 52
  • 1
    Parameters are passed on the call stack, and you're trying to pass a million parameters to `Math.min()`. – Pointy Sep 02 '20 at 12:26

2 Answers2

2

I think you experienced a stackOverFlow. The browser allocates finite memory to your Javascript call stack. As @Pointy mentioned in a comment, you tried to pass 1 million parameters. While your code might be short, it is equivelant to:

const arr = new Array(1000000)
Math.min(arr[0], arr[1], arr[2] ... arr[100,000] ... arr[999,999])

It makes sense that your JS environment can't handle it.

https://stackoverflow.com/a/13440842/7224430 refers to this issue and simply suggests iterating over the array to find the smallest.

Probably a more efficient solution is to build a dedicated function that divides your array to smaller groups that the environment can handle. After finding the minimum of each group, the minimum of minimums is the minimum of the entire group.

On a side note, I recommend not polluting the Array prototype. I know that Find the min/max element of an Array in JavaScript (and other answers) recommend it, but polluting Array's prototype isn't safe, as you might affect third party libraries.

Ben Carp
  • 24,214
  • 9
  • 60
  • 72
1

So basically when you are defining an array with a higher size and using the spread operator javascript call stack is getting full. Also even if it works for 100000 elements the performance will be worst.

If you want to work (find min and max) on the large array, it's always better to use for loop.

Nitzy
  • 264
  • 1
  • 9