A through2 wrapper to emulate Array.prototype.reduce for streams.
through2-reduce is a thin wrapper around through2 that works like
Array.prototype.reduce but for streams.
This is a much less common use-case with streams, but it can occasionally be useful to do a Reduce function on a stream.
EXPERIMENTAL This is a bit of a bizarre one, so I wouldn't be surprised if there are some dangerous edge cases around flushing and pausing and such. Use at your own risk.
This stream will only ever emit a single chunk. For more traditional
stream.Transform filters or transforms, consider
Also, if your stream never ends, Reduce will never end.
var reduce = require"through2-reduce"var sum = reduceobjectMode: true return previous + current// vs. with through2:if thistotal == undefinedthistotal = valuereturn callbackthistotal += valuethispushthisvaluereturn callbackvar sum = through2objectMode: true combine flush// Then use your reduce: (e.g. source is an objectMode stream of numbers)sourcepipesumpipesink// Works like `Array.prototype.reduce` meaning you can specify a function that// takes up to three* arguments: fn(previous, current, index) AND you can specify// an initial valuevar mean = reduceobjectMode: truereturn prev - prev - curr / index + 10
arraycallback argument. That would require realizing the entire stream, which is generally counter-productive to stream operations.
Array.prototype.reducedoesn't modify the source Array, which is somewhat nonsensical when applied to streams.
reduce([options,] fn [,initial])
Create a Reduce instance
reduce.ctor([options,] fn [,initial])
Create a Reduce class