@dvcol/common-utils
Version:
Typescript library for common utility functions and constants
56 lines (54 loc) • 2.16 kB
text/typescript
type AnyFunction<Return, Params extends any[] = any[]> = (...args: Params) => Promise<Return> | Return;
type AnySyncFunction<Return, Params extends any[] = any[]> = (...args: Params) => Return;
type Timeout = ReturnType<typeof setTimeout>;
type Ref<T> = {
value: T;
};
type DebouncedFunction<Result, Cancel = void, Fn extends AnyFunction<Result> = AnyFunction<Result>> = {
(...args: Parameters<Fn>): Promise<Result>;
/**
* The timeout currently running if any.
*/
timout?: Timeout;
/**
* Cancel the running timeout, but does not reject/resolve the outsanding promise.
* To manually reject/resolve the debounce, please use `resolve` or `reject`
*/
cancel: () => Promise<Cancel | undefined>;
/**
* Resolve the current promise early and clear timeout
* @param value
*/
resolve: (value: Result) => void;
/**
* Reject the current promise early and clear timeout
* @param error
*/
reject: (error: unknown) => void;
/**
* The arguments passed to the previous call (used for cancel callback)
*/
previous: Parameters<Fn>;
/**
* The current promise (if any)
*/
promise: Promise<Result> | undefined;
};
/**
* Debounce function that will wait for the delay to pass before executing the function.
* @param func The function to debounce.
* @param delay The delay in milliseconds. (default 250 ms)
* @param timout The timeout reference.
* @param cancel A function to run (with n-1 arguments) when a debounced call is canceled (i.e. before the delay).
*/
declare function debounce<Result, Cancel>(func: AnyFunction<Result>, delay?: number, timout?: Ref<Timeout | undefined>, cancel?: AnySyncFunction<Cancel>): DebouncedFunction<Result, Cancel, typeof func>;
declare function useDebounce<Result>({ fn, cancel, delay, timeout, }: {
fn: AnyFunction<Result>;
cancel?: AnyFunction<unknown>;
delay?: number;
timeout?: Ref<Timeout | undefined>;
}): {
debounce: (...args: Parameters<typeof fn>) => Promise<Result>;
cancel: () => unknown | Promise<unknown>;
};
export { type DebouncedFunction, debounce, useDebounce };