Problem
Implement a debounce utility in JavaScript/TypeScript.
Write a function:
function debounce<T extends (...args: any[]) => any>(
func: T,
wait: number,
options?: { leading?: boolean; trailing?: boolean }
): (...args: Parameters<T>) => void
that returns a new function debounced. When debounced is invoked repeatedly, it delays invoking func until wait milliseconds have elapsed since the most recent call.
Requirements
-
By default, behave like classic trailing-edge debounce:
-
func
runs
once
,
wait
ms after the
last
call to
debounced
.
-
Follow-up:
Support
leading debounce
via
options.leading
:
-
If
leading: true
, invoke
func
immediately on the first call in a burst.
-
Subsequent calls within the
wait
window should not invoke
func
again.
-
If
options.trailing
is supported (optional), define behavior clearly (e.g., allow trailing call even when
leading: true
).
-
Preserve
this
binding and pass through the latest arguments according to your chosen semantics.
Clarifications to handle
-
wait
is a non-negative integer.
-
Assume a browser/Node environment with
setTimeout
/
clearTimeout
.
Additional follow-up
-
State the
time and space complexity
of each call to the returned debounced function.