Skip to content

Commit

Permalink
Merge pull request #3 from bjrmatos/master
Browse files Browse the repository at this point in the history
make it more exactly like bluebird's Promise.reduce
  • Loading branch information
yoshuawuyts committed Jul 7, 2016
2 parents d2b4cf2 + 858be84 commit b094397
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 3 deletions.
15 changes: 13 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,20 @@ function reduce(fn, start) {
assert.equal(typeof fn, 'function')
return function(val) {
val = Array.isArray(val) ? val : [val]
return val.reduce(function (promise, curr) {

const length = val.length;

if (length === 0) {
return Promise.resolve(start);
}

return val.reduce(function (promise, curr, index, arr) {
return promise.then(function (prev) {
return fn(prev, curr)
if (prev === undefined && length === 1) {
return curr;
}

return fn(prev, curr, index, arr)
})
}, Promise.resolve(start))
}
Expand Down
48 changes: 47 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ test('promise-reduce should assert input types', function (t) {
t.throws(reduce.bind(null, 123))
})

test('promise-reuduce should accept a single val', function (t) {
test('promise-reduce should accept a single val', function (t) {
t.plan(1)

const res = Promise.resolve(2)
Expand Down Expand Up @@ -38,6 +38,30 @@ test('promise-reduce should reduce a fn', function (t) {
}
})

test('should pass reducer arguments to callback', function(t) {
const arrTest = [1, 2]

const res = Promise.resolve(arrTest)
.then(reduce(reduceFn, 0))
.then(checkFn)

function reduceFn(prev, next, index, arr) {
t.equal(4, arguments.length)
t.equal(arrTest, arr)

return new Promise(function (resolve) {
setTimeout(function () {
resolve(prev + next)
}, 1)
})
}

function checkFn(val) {
t.equal(3, val)
t.end()
}
})

test('should not continue until last iteration has been resolved', function (t) {
t.plan(1)
const res = Promise.resolve([1, 2, 3])
Expand All @@ -56,3 +80,25 @@ test('should not continue until last iteration has been resolved', function (t)
t.equal(6, val)
}
})

test('should not call callback when initial value is undefined and iterable contains one item', function (t) {
t.plan(1)
const res = Promise.resolve([1])
.then(reduce(function() {}, undefined))
.then(checkFn)

function checkFn(val) {
t.equal(1, val, 'should return the item in iterable')
}
})

test('should not call callback when iterable is empty', function (t) {
t.plan(1)
const res = Promise.resolve([])
.then(reduce(function() {}, 10))
.then(checkFn)

function checkFn(val) {
t.equal(10, val, 'should return initial value')
}
})

0 comments on commit b094397

Please sign in to comment.