1
0
Fork 0
functional/composition.ts

39 lines
898 B
TypeScript

/**
* Functions that does nothing (useful for default callbacks)
*/
export function nop(...args: any[]): any {
}
/**
* Identity function (returns the sole argument untouched)
*/
export function identity<T>(input: T): T {
return input;
}
/**
* Partially apply fixed arguments to a function with named arguments
*/
export function partial<
A extends object,
PA extends Partial<A>,
RA extends any[],
R,
>(
fixedargs: PA,
func: (args: A, ...rest: RA) => R,
): (args: Omit<A, keyof PA>, ...rest: RA) => R {
return (args: Omit<A, keyof PA>, ...rest: RA) =>
func({ ...fixedargs, ...args } as any, ...rest);
}
/**
* Pipe the result of a function as first parameter of another, to create a new function
*/
export function pipe<IN extends any[], INT, R>(
f1: (...args: IN) => INT,
f2: (value: INT) => R,
): (...args: IN) => R {
return (...args: IN) => f2(f1(...args));
}