export interface NextAsyncProcessor { (input: TInput): Promise; } export interface AsyncProcessor { (next: NextAsyncProcessor): NextAsyncProcessor; } export interface NextSyncProcessor { (input: TInput): TOutput; } export interface SyncProcessor { (next: NextSyncProcessor): NextSyncProcessor; } export function composeAsync( functions: Array> = [] ): NextAsyncProcessor { return (input: TInput): Promise => { if (!functions.length) { return Promise.resolve(input as unknown as TOutput); } let index = -1; const next: NextAsyncProcessor = async input => { index++; const fn = functions[index]; if (!fn) { return input as unknown as TOutput; } return fn(next)(input); }; return next(input); }; } export function composeSync( functions: Array> = [] ): NextSyncProcessor { return (input: TInput): TOutput => { if (!functions.length) { return input as unknown as TOutput; } // Create a clone of function chain to prevent modifying the original array with `shift()` let index = -1; const next: NextSyncProcessor = input => { index++; const fn = functions[index]; if (!fn) { return input as unknown as TOutput; } return fn(next)(input); }; return next(input); }; }