Skip to content

Instantly share code, notes, and snippets.

@TTSKarlsson
Created July 12, 2021 10:25
Show Gist options
  • Save TTSKarlsson/a51efc02b94f4a5910915bfc347b25a3 to your computer and use it in GitHub Desktop.
Save TTSKarlsson/a51efc02b94f4a5910915bfc347b25a3 to your computer and use it in GitHub Desktop.
Typescript Pipeline operator function, for until |> operator becomes official
/**
* 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