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 */
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With