Created
July 28, 2020 17:57
-
-
Save johncmunson/0c03d5223f247d32b84246112a81c1e2 to your computer and use it in GitHub Desktop.
Debounce a function, with the option to accumulate args
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function debounce(delay, callback, accumulateData) { | |
let timeout = null | |
let data = [] | |
return function () { | |
if (accumulateData) { | |
const arr = [] | |
for (let i = 0; i < arguments.length; ++i) { | |
arr.push(arguments[i]) | |
} | |
data.push(arr) | |
} | |
if (timeout) { | |
clearTimeout(timeout) | |
} | |
const args = arguments | |
timeout = setTimeout(function () { | |
callback.apply((accumulateData) ? { data } : null, args) | |
data = [] | |
timeout = null | |
}, delay) | |
} | |
} | |
// Unit tests should illustrate pretty well what this function does... | |
import { debounce } from '../../../src/util' | |
jest.useFakeTimers() | |
describe('util', () => { | |
describe('debounce', () => { | |
it('debounces the function', () => { | |
const target = jest.fn() | |
const func = function(int) { | |
target(int) | |
} | |
const debouncedFunc = debounce(1000, func, false) | |
debouncedFunc(1) | |
debouncedFunc(2) | |
debouncedFunc(3) | |
jest.runAllTimers() | |
expect(target).toHaveBeenCalledTimes(1) | |
expect(target).toHaveBeenCalledWith(3) | |
}) | |
it('debounces the function and accumulates args', () => { | |
const target = jest.fn() | |
const func = function(int) { | |
target(this.data) | |
} | |
const debouncedFunc = debounce(1000, func, true) | |
debouncedFunc(1) | |
debouncedFunc(2) | |
debouncedFunc(3) | |
jest.runAllTimers() | |
debouncedFunc(4) | |
jest.runAllTimers() | |
expect(target).toHaveBeenCalledTimes(2) | |
expect(target.mock.calls[0][0]).toEqual([[ 1 ], [ 2 ], [ 3 ]]) | |
expect(target.mock.calls[1][0]).toEqual([[ 4 ]]) | |
}) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment