Math.max() returns the largest of zero or more numbers passed to it. We can use the spread operator when passing an array to get the largest number...
For further actions, you may consider blocking this person and/or reporting abuse
In any sane programming language, you'd just do
but alas, JS masterfully breaks every existing pattern except those coming from C.
I think you're picking a hole in JS where there isn't one, except, perhaps, in the
Math.maxfunction. You could easily create a function which will work very happily with reduce:Nice alternative! That is the way I used to do this before the spread operator. Works just as well.
You might want to safeguard this with Number.NEGATIVE_INFINITY as the initial value in
reducein case of an empty array.Math.max()also returns-Infinitywhen called without any parameters.That'd surely be worth doing, I really only added that code to give an example close to the code that was quoted.
Fair enough. 👍
There definitely is. The problem here is a clash between two good intentions:
The first one is unnecessary. It's only a bit more convenient to write
max(a, b, c)than[a, b, c].fold(max), but it's still something that makes sense.The second one, on the other hand, is a giant footgun. It only makes sense in the context of optimization, as using
mapfirst would result in one temporary array being created, but that should be optimized by the language runtime via stream fusion, not by the specification of the function. Ultimately it will just lead to more confusing code full of functions that do too many things at once, giving it a very procedural feel.As for your solution, that's basically what I did, except that I wrote the function inline. Another solution would be:
Which, to prevent monkey-patching, sadly loses the method-syntax which makes chaining easier to read.
If you don't have to deal with large arrays (more than 100000 elements), then this approach works fine.
However if the array is large, please bear in mind that JavaScript runtimes have a limitation on the number of arguments that you can pass to a function. Yes, this include spread parameters.
If you pass more arguments than the limit, “Maximum call stack size exceeded” errors happen.
I have to find the maximum and minimum value of very huge arrays. For this I'm using
It works good on Firefox and IE, but on Chrome I always get
Maximum call stack size exceedederrors... my current array has 221954 elements, and that's not my…It looks like this works, too.