How To Avoid Stack Overflow When Applying Max To A Large Array In Javascript?
The following code var interval = function (a, b) { var i, list = []; for (i = a; i <= b; i++) { list.push(i); } return list;
Solution 1:
The issue here is with the line:
Math.max.apply(null, xs);
You are trying to call Math.max(1, 2, 3, 4, ..., 500000);
. JavaScript doesn't like calling a function with 500,000 parameters.
See this answer for more info: https://stackoverflow.com/a/22747272
Solution 2:
If you want a work around, you can use underscore.js
From the source code, it looks like they just loop through the elements using a for loop
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value > result) {
result = value;
}
}
Here is an example in JSFiddle
var interval = function (a, b) {
var i, list = [];
for (i = a; i <= b; i++) {
list.push(i);
}
return list;
},
xs = interval(1, 500000);
console.log(_.max(xs))
//prints 500000
Post a Comment for "How To Avoid Stack Overflow When Applying Max To A Large Array In Javascript?"