mirror of
https://github.com/zoriya/v10.git
synced 2026-08-16 02:45:09 +00:00
24 lines
700 B
TypeScript
24 lines
700 B
TypeScript
import { isNil } from '../predicate';
|
|
|
|
/**
|
|
* Composes multiple callbacks into one. All callbacks receive same args, no return value.
|
|
* Returns undefined if no callbacks provided.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const onSetup = composeCallbacks(base.onSetup, extension.onSetup);
|
|
* onSetup?.(ctx); // Calls both if defined
|
|
* ```
|
|
*/
|
|
export function composeCallbacks<T extends (...args: any[]) => void>(...fns: (T | undefined | null)[]): T | undefined {
|
|
const defined = fns.filter((fn): fn is T => !isNil(fn));
|
|
|
|
if (defined.length === 0) return undefined;
|
|
|
|
if (defined.length === 1) return defined[0];
|
|
|
|
return ((...args: Parameters<T>) => {
|
|
defined.forEach((fn) => fn(...args));
|
|
}) as T;
|
|
}
|