Skip to content

Instantly share code, notes, and snippets.

@tonitrnel
Last active January 5, 2023 03:38
Show Gist options
  • Save tonitrnel/860d891913953f831fc008fa0f857a54 to your computer and use it in GitHub Desktop.
Save tonitrnel/860d891913953f831fc008fa0f857a54 to your computer and use it in GitHub Desktop.
type PipeCurrying<T> = <F extends ((previousValue: T) => unknown) | undefined>(value?: F) => undefined extends F ? T : PipeCurrying<F extends (value: T) => infer R ? R : unknown>
/**
* Pipe function
* @example pipe(123)() // 123
* @example pipe(123)(v => v + 456)() // 579
* @example pipe({a: 3})(v => v.a)(v => v * 15)(v => v.toString(16))(v => '0x' + v)() // 0x2d
*/
function pipe<T>(initialValue: T): PipeCurrying<T> {
return ((value?: (previousValue: T) => unknown) => {
if (value === void 0) return initialValue
else return pipe(value(initialValue))
}) as PipeCurrying<T>
}
const r = pipe(3)(v => v.toString())(v => parseInt(v))(v => v + 2)
console.log(r)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment