interface DebounceOptions { emitLast?: boolean; } /** * Debounces a function by waiting `delay` ms after the last call before executing it. * If `emitLast` is false, it cancels the call instead of delaying it. */ export const debounce = ) => void | Promise>( func: T, delay: number, options: DebounceOptions = { emitLast: true }, ): ((...args: Parameters) => void) => { let timeout: ReturnType | null = null; let lastArgs: Parameters | null = null; return (...args: Parameters): void => { if (timeout) { clearTimeout(timeout); } if (options.emitLast) { lastArgs = args; timeout = setTimeout(() => { if (lastArgs) { func(...(lastArgs as Parameters)); lastArgs = null; } timeout = null; }, delay); } else { timeout = setTimeout(() => { func(...args); timeout = null; }, delay); } }; };