Skip to content

Instantly share code, notes, and snippets.

@nexxeln
Created January 21, 2023 16:13
Show Gist options
  • Save nexxeln/4c201c783571b5b905618c9533b0c0cc to your computer and use it in GitHub Desktop.
Save nexxeln/4c201c783571b5b905618c9533b0c0cc to your computer and use it in GitHub Desktop.
function pipe<A>(value: A): A;
function pipe<A, B>(value: A, fn1: (input: A) => B): B;
function pipe<A, B, C>(value: A, fn1: (input: A) => B, fn2: (input: B) => C): C;
function pipe<A, B, C, D>(
value: A,
fn1: (input: A) => B,
fn2: (input: B) => C,
fn3: (input: C) => D
): D;
function pipe<A, B, C, D, E>(
value: A,
fn1: (input: A) => B,
fn2: (input: B) => C,
fn3: (input: C) => D,
fn4: (input: D) => E
): E;
// ... and so on
function pipe(value: any, ...fns: Function[]): unknown {
return fns.reduce((acc, fn) => fn(acc), value);
}
// BUT YOU CAN DO THIS IN AN INTERFACE AND USE ARROW FUNCTIONS LIKE A SANE PERSON
interface Pipe {
<A>(value: A): A;
<A, B>(value: A, fn1: (input: A) => B): B;
<A, B, C>(value: A, fn1: (input: A) => B, fn2: (input: B) => C): C;
<A, B, C, D>(
value: A,
fn1: (input: A) => B,
fn2: (input: B) => C,
fn3: (input: C) => D
): D;
<A, B, C, D, E>(
value: A,
fn1: (input: A) => B,
fn2: (input: B) => C,
fn3: (input: C) => D,
fn4: (input: D) => E
): E;
// ... and so on
}
const pipee: Pipe = (value: any, ...fns: Function[]): unknown => {
return fns.reduce((acc, fn) => fn(acc), value);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment