Problem Statement
Different use cases require different debounce behaviors. Implement a flexible debounce function that supports configuration for both leading and trailing edge execution.
Requirements
Implement a debounce(func, wait, options) function where options include:
leading(boolean, default: false) - invoke on the leading edgetrailing(boolean, default: true) - invoke on the trailing edge
Example Usage
const log = (msg) => console.log(msg);
// Trailing only (default)
const trailingDebounce = debounce(log, 100, { leading: false, trailing: true });
trailingDebounce("a");
trailingDebounce("b");
// After 100ms: logs "b"
// Leading only
const leadingDebounce = debounce(log, 100, { leading: true, trailing: false });
leadingDebounce("a"); // Logs "a" immediately
leadingDebounce("b"); // Ignored
// Nothing after 100ms
// Both edges
const bothDebounce = debounce(log, 100, { leading: true, trailing: true });
bothDebounce("a"); // Logs "a" immediately
bothDebounce("b");
bothDebounce("c");
// After 100ms: logs "c"Edge Cases to Consider
- What happens when both leading and trailing are false?
- What if the function is called exactly once?
- How do you handle rapid calls that span multiple wait periods?
Follow-up Questions
- How would Lodash's debounce handle this scenario?
- What are the tradeoffs of this API design?