Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum call stack size exceeded when using the dots operator

Tags:

javascript

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 */
like image 893
kfx Avatar asked Jul 03 '26 22:07

kfx


1 Answers

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.

like image 116
Ben Carp Avatar answered Jul 06 '26 13:07

Ben Carp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!