From 8d7bd851c098b2688974f8931091d673bdb39625 Mon Sep 17 00:00:00 2001 From: Edgar To Date: Thu, 25 Oct 2018 19:10:09 +0200 Subject: [PATCH] allow accumulate to work with single or no result some debounced functions does not need to return something or return a conclusion of what happened --- index.js | 8 +++++++- test/index.js | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 6d570e1..e20a336 100644 --- a/index.js +++ b/index.js @@ -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 diff --git a/test/index.js b/test/index.js index 791ed7d..3b42f23 100644 --- a/test/index.js +++ b/test/index.js @@ -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) {