Skip to content

Commit

Permalink
make initial reduce() accumulator value optional
Browse files Browse the repository at this point in the history
  • Loading branch information
kemitchell committed Oct 22, 2016
1 parent 9d9abd2 commit 68817be
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
32 changes: 26 additions & 6 deletions sinks/reduce.js
Expand Up @@ -2,11 +2,31 @@

var drain = require('./drain')

module.exports = function reduce (reducer, acc, cb) {
return drain(function (data) {
acc = reducer(acc, data)
}, function (err) {
cb(err, acc)
})
module.exports = function reduce (/* reducer, acc, cb */) {
var reducer = arguments[0]
var acc
var cb
if (arguments.length === 3) {
acc = arguments[1]
cb = arguments[2]
return drain(function (data) {
acc = reducer(acc, data)
}, function (err) {
cb(err, acc)
})
} else {
cb = arguments[1]
var first = true
return drain(function (data) {
if (first) {
acc = data
first = false
} else {
acc = reducer(acc, data)
}
}, function (err) {
cb(err, acc)
})
}
}

10 changes: 10 additions & 0 deletions test/drain-if.js
Expand Up @@ -12,6 +12,16 @@ test('reduce becomes through', function (t) {
)
})

test('reduce without initial value', function (t) {
pull(
pull.values([1,2,3]),
pull.reduce(function (a, b) {return a + b}, function (err, val) {
t.equal(val, 6)
t.end()
})
)
})


test('reduce becomes drain', function (t) {
pull(
Expand Down

0 comments on commit 68817be

Please sign in to comment.