Commit 0638fd964786330ea637fe10af73a9474d43493d
another way to implement reduce with default initial value
Dominic Tarr committed on 10/24/2016, 7:32:52 PMParent: 68817beb980ea6e170598acc630b7ea873d76193
Files changed
sinks/reduce.js | changed |
sinks/reduce.js | ||
---|---|---|
@@ -5,28 +5,24 @@ | ||
5 | 5 | module.exports = function reduce (/* reducer, acc, cb */) { |
6 | 6 | var reducer = arguments[0] |
7 | 7 | var acc |
8 | 8 | var cb |
9 | - if (arguments.length === 3) { | |
9 | + var sink = drain(function (data) { | |
10 | + acc = reducer(acc, data) | |
11 | + }, function (err) { | |
12 | + cb(err, acc) | |
13 | + }) | |
14 | + if (arguments.length === 2) { | |
15 | + cb = arguments[2] | |
16 | + return function (source) { | |
17 | + source(null, function (end, data) { | |
18 | + //if ended immediately, and no initial... | |
19 | + if(end) return cb(end === true ? null : end) | |
20 | + acc = data; sink(source) | |
21 | + }) | |
22 | + } | |
23 | + } else { | |
10 | 24 | acc = arguments[1] |
11 | 25 | 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 | - }) | |
26 | + return sink | |
30 | 27 | } |
31 | 28 | } |
32 | - |
Built with git-ssb-web