Proposal: Array.prototype.accumulate and Array.prototype.accumulateRight

# Mark M. Young (8 years ago)

I am proposing a replacement for Array.prototype.reduce and Array.prototype.reduceRight. The main improvements are 1) iteration always starts at index 0 (or k-1 in the case of accumulateRight) on non-empty arrays and 2) it allows definition of callbackFn's ‘this' context just like ‘every’, ‘filter’, ‘find’, ‘findIndex’, ‘forEach’, ‘map', and ‘some’.

The code is simple, but I have included much explanation because of the blank stares I get from people when I say “the problem with Array reduce” so I anticipate resistance. Please visit the GitHub repo. and review on here.

MarkMYoung/ArrayAccumulate, MarkMYoung/ArrayAccumulate

# Bergi (8 years ago)

Mark M. Young wrote:

I am proposing a replacement for Array.prototype.reduce and Array.prototype.reduceRight.

Nice. Allowing to pass an argument for the this value was missing when folding an array, and your suggestion accumulate is a fitting method name.

However, I fear the use cases are too unimportant to need a fix. The this keyword is becoming less and less used for anything but class methods. And for those, arrow functions solve the problem needing to invoke functions on the expected receiver. For passing in data to a reusable reducer function, closures are much simpler than setting the this value for the callback.

MarkMYoung/ArrayAccumulate, MarkMYoung/ArrayAccumulate says

reduce is not reusable code because there is no way to know what the second parameter was once beyond the first iteration.

That makes no sense. The whole point of the initial value parameter is that it only goes into the first call (if any), or is the return value in case the array is empty.

the second parameter is always available as this.

It really should not be. If you want to pass a value for this, it needs a third parameter.

kind , Bergi

# Alexander Jones (8 years ago)

Can we please start talking about Iterators already? The Python community are laughing at us! Widening the Array prototype is like putting lipstick on a pig...