Skip to content

Commit

Permalink
allow accumulate to work with single or no result
Browse files Browse the repository at this point in the history
some debounced functions does not need to return something or return a 
conclusion of what happened
  • Loading branch information
EdJoPaTo committed Oct 25, 2018
1 parent cf5283c commit 8d7bd85
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
8 changes: 7 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,13 @@ module.exports = function debounce (fn, wait = 0, options = {}) {

if (options.accumulate) {
const argsIndex = pendingArgs.length - 1
return deferred.promise.then(results => results[argsIndex])
return deferred.promise.then(results => {
if (Array.isArray(results)) {
return results[argsIndex]
} else {
return results
}
})
}

return deferred.promise
Expand Down
35 changes: 35 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,41 @@ test('calls debounced function and accumulates arguments', async t => {
t.equal(await three, 9)
})

test('accumulate works with single result value', async t => {
function someTaskRequiresAttention (args) {
t.deepEqual(args, [[1], [5], [15]])
return Promise.resolve(
args
.map(o => o[0])
.some(o => o > 10)
)
}

const debounced = debounce(someTaskRequiresAttention, 10, {accumulate: true})

const one = debounced(1)
const two = debounced(5)
const three = debounced(15)

t.true(await one)
t.true(await two)
t.true(await three)
})

test('accumulate works without result', async t => {
let callCount = 0
async function doSomethingLessOften (args) {
t.deepEqual(args, [[1], [5], [15]])
callCount++
await sleep(5)
}

const debounced = debounce(doSomethingLessOften, 10, {accumulate: true})

await Promise.all([1, 5, 15].map(o => debounced(o)))
t.equal(callCount, 1)
})

test('accumulate works with leading=true', async t => {
let callNo = 1
function squareBatch (args) {
Expand Down

0 comments on commit 8d7bd85

Please sign in to comment.