Created
July 12, 2021 10:25
-
-
Save TTSKarlsson/a51efc02b94f4a5910915bfc347b25a3 to your computer and use it in GitHub Desktop.
Typescript Pipeline operator function, for until |> operator becomes official
This file contains hidden or 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
/** | |
* Pipeline operator function, for until |> operator becomes official | |
* Usage: | |
* | |
* ```ts | |
* const doubleIt = (x:number)=>x*2 | |
* const withExclamation = (x:any)=>`${x}!` | |
* pipe(15, doubleIt, withExclamation) // : "30!" | |
* ``` | |
* | |
* @returns The result of the last function in the pipe | |
*/ | |
export const pipe = < | |
F extends (...args: Readonly<any[]>) => any, | |
A extends F[], | |
V | |
>( | |
value: V, | |
...args: A | |
) => { | |
return args.reduce((acc, f) => f(acc), value) as ReturnType<Last<A>> | |
} | |
type Tail<T extends readonly any[]> = ((...t: T) => void) extends ( | |
h: any, | |
...r: infer R | |
) => void | |
? R | |
: never | |
type Last<T extends readonly any[]> = number extends T['length'] | |
? T[1e100] | |
: { | |
[K in keyof T]: K extends keyof Tail<T> ? never : T[K] | |
}[number] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment