|
| 1 | +/** @see https://github.com/reduxjs/redux/blob/master/src/compose.ts */ |
| 2 | + |
| 3 | +type Func<T extends any[], R> = (...a: T) => R; |
| 4 | + |
| 5 | +/** |
| 6 | + * Composes single-argument functions from right to left. The rightmost |
| 7 | + * function can take multiple arguments as it provides the signature for the |
| 8 | + * resulting composite function. |
| 9 | + * |
| 10 | + * @param funcs The functions to compose. |
| 11 | + * @returns A function obtained by composing the argument functions from right |
| 12 | + * to left. For example, `compose(f, g, h)` is identical to doing |
| 13 | + * `(...args) => f(g(h(...args)))`. |
| 14 | + */ |
| 15 | +function compose(): <R>(a: R) => R; |
| 16 | + |
| 17 | +function compose<F extends Function>(f: F): F; |
| 18 | + |
| 19 | +/* two functions */ |
| 20 | +function compose<A, T extends any[], R>(f1: (a: A) => R, f2: Func<T, A>): Func<T, R>; |
| 21 | + |
| 22 | +/* three functions */ |
| 23 | +function compose<A, B, T extends any[], R>( |
| 24 | + f1: (b: B) => R, |
| 25 | + f2: (a: A) => B, |
| 26 | + f3: Func<T, A>, |
| 27 | +): Func<T, R>; |
| 28 | + |
| 29 | +/* four functions */ |
| 30 | +function compose<A, B, C, T extends any[], R>( |
| 31 | + f1: (c: C) => R, |
| 32 | + f2: (b: B) => C, |
| 33 | + f3: (a: A) => B, |
| 34 | + f4: Func<T, A>, |
| 35 | +): Func<T, R>; |
| 36 | + |
| 37 | +/* rest */ |
| 38 | +function compose<R>(f1: (a: any) => R, ...funcs: Function[]): (...args: any[]) => R; |
| 39 | + |
| 40 | +function compose<R>(...funcs: Function[]): (...args: any[]) => R; |
| 41 | + |
| 42 | +function compose(...funcs: Function[]) { |
| 43 | + if (funcs.length === 0) { |
| 44 | + // infer the argument type so it is usable in inference down the line |
| 45 | + return <T>(arg: T) => arg; |
| 46 | + } |
| 47 | + |
| 48 | + if (funcs.length === 1) { |
| 49 | + return funcs[0]; |
| 50 | + } |
| 51 | + |
| 52 | + return funcs.reduce((a, b) => (...args: any) => a(b(...args))); |
| 53 | +} |
| 54 | + |
| 55 | +export default compose; |
0 commit comments