Commit 68817beb980ea6e170598acc630b7ea873d76193
make initial reduce() accumulator value optional
Kyle E. Mitchell committed on 10/22/2016, 2:31:15 AMParent: 9d9abd26492b94a6b650b38e7db4ef41257d64d7
Files changed
sinks/reduce.js | changed |
test/drain-if.js | changed |
sinks/reduce.js | ||
---|---|---|
@@ -1,12 +1,32 @@ | ||
1 | 1 | |
2 | 2 | |
3 | 3 | var drain = require('./drain') |
4 | 4 | |
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 | + } | |
11 | 31 | } |
12 | 32 |
test/drain-if.js | ||
---|---|---|
@@ -11,9 +11,19 @@ | ||
11 | 11 | }) |
12 | 12 | ) |
13 | 13 | }) |
14 | 14 | |
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 | +}) | |
15 | 24 | |
25 | + | |
16 | 26 | test('reduce becomes drain', function (t) { |
17 | 27 | pull( |
18 | 28 | pull.values([1,2,3]), |
19 | 29 | pull.reduce( |
Built with git-ssb-web