Problem Statement
In React applications and complex UIs, we need the ability to cancel pending throttled operations (e.g., on component unmount) and flush pending calls immediately (e.g., before navigation). Implement a throttle with full lifecycle control.
Requirements
Implement a throttle(func, wait) function that returns a throttled function with:
cancel()- cancels any pending trailing invocationflush()- immediately executes pending trailing invocation (if any)pending()- returns boolean indicating if a trailing call is pending- Both leading and trailing enabled by default
Example Usage
Implementation Considerations
- flush() should be idempotent if nothing is pending
- cancel() should not affect the next leading call
- Methods should be safely callable at any time
Follow-up Questions
- Should flush() return the result of the function call?
- How do you handle the case where flush() is called during execution?