Skip to content

Instantly share code, notes, and snippets.

@Saul-Mirone
Last active August 6, 2022 12:45
Show Gist options
  • Save Saul-Mirone/f1093994013d235fdc9cc79a34002279 to your computer and use it in GitHub Desktop.
Save Saul-Mirone/f1093994013d235fdc9cc79a34002279 to your computer and use it in GitHub Desktop.
type Many<T> = T | ReadonlyArray<T>;
interface Flow {
flow<A extends any[], R1, R2, R3, R4, R5, R6, R7>(
f1: (...args: A) => R1,
f2: (a: R1) => R2,
f3: (a: R2) => R3,
f4: (a: R3) => R4,
f5: (a: R4) => R5,
f6: (a: R5) => R6,
f7: (a: R6) => R7,
): (...args: A) => R7;
flow<A extends any[], R1, R2, R3, R4, R5, R6, R7>(
f1: (...args: A) => R1,
f2: (a: R1) => R2,
f3: (a: R2) => R3,
f4: (a: R3) => R4,
f5: (a: R4) => R5,
f6: (a: R5) => R6,
f7: (a: R6) => R7,
...func: Array<Many<(a: any) => any>>
): (...args: A) => any;
flow<A extends any[], R1, R2, R3, R4, R5, R6>(
f1: (...args: A) => R1,
f2: (a: R1) => R2,
f3: (a: R2) => R3,
f4: (a: R3) => R4,
f5: (a: R4) => R5,
f6: (a: R5) => R6,
): (...args: A) => R6;
flow<A extends any[], R1, R2, R3, R4, R5>(
f1: (...args: A) => R1,
f2: (a: R1) => R2,
f3: (a: R2) => R3,
f4: (a: R3) => R4,
f5: (a: R4) => R5,
): (...args: A) => R5;
flow<A extends any[], R1, R2, R3, R4>(
f1: (...args: A) => R1,
f2: (a: R1) => R2,
f3: (a: R2) => R3,
f4: (a: R3) => R4,
): (...args: A) => R4;
flow<A extends any[], R1, R2, R3>(f1: (...args: A) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (...args: A) => R3;
flow<A extends any[], R1, R2>(f1: (...args: A) => R1, f2: (a: R1) => R2): (...args: A) => R2;
flow(...func: Array<Many<(...args: any[]) => any>>): (...args: any[]) => any;
}
const flow: Flow['flow'] = (...funcs: any[]) => {
const length = funcs.length;
let index = length;
while (index--) {
if (typeof funcs[index] !== 'function') {
throw new TypeError('Expected a function');
}
}
return (...args: any[]) => {
let index = 0;
let result = length ? funcs[index].apply(this, args) : args[0];
while (++index < length) {
result = funcs[index].call(this, result);
}
return result;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment