Created
June 22, 2021 16:46
-
-
Save SagnikPradhan/6699042c894544b19d0a9018399c88d0 to your computer and use it in GitHub Desktop.
⛓️ Chain functions as arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type Fn<Input = any, Output = any> = (input: Input) => Output; | |
export type Chain<Fns extends Fn[]> = | |
// We chain two functions at one time | |
Fns extends [infer Fn1, infer Fn2, ...infer RestFns] | |
? // Make sure two elements are functions | |
Fn1 extends Fn<infer Fn1Argument> | |
? Fn2 extends Fn<infer Fn2Argument> | |
? RestFns extends Fn[] | |
? // Rest of the elements exist | |
[Fn<Fn1Argument, Fn2Argument>, ...Chain<[Fn2, ...RestFns]>] | |
: // Only two elements | |
[Fn<Fn1Argument, Fn2Argument>, Fn2] | |
: // Second element not a function | |
[Fn1] | |
: // First element not a function | |
never | |
: // Seems like we don't have two elements | |
Fns extends [infer Fn] | |
? [Fn] | |
: // The only element is not a function | |
never; | |
// Try chaining functions in an array on this function. | |
function chain<Fns extend Fn[]>(...fns: Fns & Chain<Fns>) {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment