git ssb

2+

Dominic / pull-stream



Commit 68817beb980ea6e170598acc630b7ea873d76193

make initial reduce() accumulator value optional

Kyle E. Mitchell committed on 10/22/2016, 2:31:15 AM
Parent: 9d9abd26492b94a6b650b38e7db4ef41257d64d7

Files changed

sinks/reduce.jschanged
test/drain-if.jschanged
sinks/reduce.jsView
@@ -1,12 +1,32 @@
11 'use strict'
22
33 var drain = require('./drain')
44
5-module.exports = function reduce (reducer, acc, cb) {
6- return drain(function (data) {
7- acc = reducer(acc, data)
8- }, function (err) {
9- cb(err, acc)
10- })
5+module.exports = function reduce (/* reducer, acc, cb */) {
6+ var reducer = arguments[0]
7+ var acc
8+ var cb
9+ if (arguments.length === 3) {
10+ acc = arguments[1]
11+ cb = arguments[2]
12+ return drain(function (data) {
13+ acc = reducer(acc, data)
14+ }, function (err) {
15+ cb(err, acc)
16+ })
17+ } else {
18+ cb = arguments[1]
19+ var first = true
20+ return drain(function (data) {
21+ if (first) {
22+ acc = data
23+ first = false
24+ } else {
25+ acc = reducer(acc, data)
26+ }
27+ }, function (err) {
28+ cb(err, acc)
29+ })
30+ }
1131 }
1232
test/drain-if.jsView
@@ -11,9 +11,19 @@
1111 })
1212 )
1313 })
1414
15+test('reduce without initial value', function (t) {
16+ pull(
17+ pull.values([1,2,3]),
18+ pull.reduce(function (a, b) {return a + b}, function (err, val) {
19+ t.equal(val, 6)
20+ t.end()
21+ })
22+ )
23+})
1524
25+
1626 test('reduce becomes drain', function (t) {
1727 pull(
1828 pull.values([1,2,3]),
1929 pull.reduce(

Built with git-ssb-web