short-circuiting Array.prototype.reduce

Bergi a.d.bergi at web.de
Fri Mar 27 04:48:27 UTC 2015


Kyle Simpson schrieb:

> Since `reduce(..)` conveniently can compare two adjacent elements if you always return the current value, I decided to model the inner check as a `reduce(..)` that reduces from the original array value to either a `false` or a truthy value (the last element of the inner array element).

Um, that's not exactly what reduction is meant for. The reduce method is 
designed so that the return values and the accumulator argument do have 
the same type. In your example, you have somehow mixed an expected 
boolean result with the item type of the array.
This leads to several bug in your implementation, which doesn't work
* with lists of booleans
* with empty arrays
* with arrays whose last element is falsy

 > The example code isn't very compelling either; something more 
real-world would be good

Well, basically all operations that return an absorbing element 
<https://en.wikipedia.org/wiki/Absorbing_element> would benefit from this.

  Bergi


More information about the es-discuss mailing list