4 ms·
Isn't the solution there to name variables well? A reduce function turns an array into a single value, passing the result of computation of each element to the
by beatgammit 7y ago
Isn't the solution there to name variables well?
A reduce function turns an array into a single value, passing the result of computation of each element to the next element. So, the signature is:
function (accumulator, element) -> accumulator
So, you take in some accumulated value (or the initial value on the first iteration) and an element and return the accumulated value to the next element. If the values were swapped, it would be inconsistent with the rest of the array functions where optional arguments are tacked on to the end (e.g. index, array), so the obvious assumption is that the accumulator goes in front to keep the rest of it as similar to the other array functions as possible.
I think it's unfortunate that array.reduce takes the accumulator after the function, but that also makes sense since it's technically valid to omit the accumulator (defaults to undefined).
The problem, I think, is that reduce is often abused when another function might make more sense (e.g. as a ghetto "find" or something). If it's used properly, I think it's quite elegant. If it's not, it's a confusing mess.