Skip to content

Commit

Permalink
Merge branch 'preread_reduce'
Browse files Browse the repository at this point in the history
  • Loading branch information
dominictarr committed Oct 31, 2016
2 parents 9e8b771 + 6c5caa6 commit 3584caa
Showing 1 changed file with 17 additions and 27 deletions.
44 changes: 17 additions & 27 deletions sinks/reduce.js
Expand Up @@ -2,31 +2,21 @@

var drain = require('./drain')

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)
})
}
module.exports = function reduce (reducer, acc, cb ) {
if(!cb) cb = acc, acc = null
var sink = drain(function (data) {
acc = reducer(acc, data)
}, function (err) {
cb(err, acc)
})
if (arguments.length === 2)
return function (source) {
source(null, function (end, data) {
//if ended immediately, and no initial...
if(end) return cb(end === true ? null : end)
acc = data; sink(source)
})
}
else
return sink
}

0 comments on commit 3584caa

Please sign in to comment.