Debounce With a Fake Clock
Hard · Functions
Write debounce(fn, wait, leading, clock). It returns a function debounced(...args) with a cancel() method. For timing, use only clock.setTimeout(callback, ms) and clock.clearTimeout(id): a fake clock that the tests move forward.
- A burst is a series of calls, each less than wait ms after the previous one. It ends wait ms after its last call.
- When a burst ends, call fn once with the arguments of its last call.
- If leading is true, also call fn right away on the first call of a burst. Then the call at the end only happens if the burst had 2 or more calls.
- cancel() drops the pending call and ends the burst.
testDebounce(wait, leading, ops) is already written. It replays ["call", ...args], ["tick", ms] and ["cancel"] and returns a log with "time:args" for every fn call.