short-circuiting Array.prototype.reduce

Kyle Simpson getify at
Fri Mar 27 05:19:12 UTC 2015

> Um, that's not exactly what reduction is meant for.

There's lots of different ways `reduce(..)` gets used in the wild; I can list several entirely distinct but common idioms right off the top of my head. Just because it's not the original intent doesn't mean it's invalid to do so.

To the point of the earlier question I was addressing, I was just giving *an* example of real code, in a very specific circumstance, where I would have liked early-exit. It was not a broad endorsement of the presented idiom as a general pattern.

> The reduce method is designed so that the return values and the accumulator argument do have the same type.

In my observation, there's nothing at all that requires that. This is certainly not the only time that I've made effective use of mixing/toggling types during reduction.

> In your example, you have somehow mixed an expected boolean result with the item type of the array.

If by "expected boolean result" you mean what `filter(..)` expects to receive, actually it doesn't require a strict boolean. It expects a truthy/falsy value (check the spec). I like coercion. I use it liberally. The values in my `inner` arrays were all truthy values (see below) and `filter(..)` works perfectly fine receiving such.

> This leads to several bug in your implementation, which doesn't work

None of those are "bugs" in my implementation, because none of those can happen within the constraints of the problem. If you re-read the stated setup for the problem I was solving, you'll see the constraints I'm referring to.

BTW, since you brought it up, for the empty `inner` array case to be supported (I didn't need it, but...), all I would need to do is `inner.reduce( function.., undefined )` (or `false` if you prefer) if I wanted empty arrays filtered out, or `inner.reduce( function.., true )` if I wanted empty arrays preserved. Easy.

> all operations that return an absorbing element...would benefit

My `false` value trigger on finding an `inner` that should be filtered out is conceptually that. From then on in the reduction, all other values are "absorbed" (aka ignored, aka overriden) by the `false`. :)

More information about the es-discuss mailing list