Skip to content

Instantly share code, notes, and snippets.

@trvswgnr
Created May 27, 2026 14:37
Show Gist options
  • Select an option

  • Save trvswgnr/56b4d2c71234bbfb2db19b38b80919d6 to your computer and use it in GitHub Desktop.

Select an option

Save trvswgnr/56b4d2c71234bbfb2db19b38b80919d6 to your computer and use it in GitHub Desktop.
ts simplest lazy pipe
const pipe = <T>(value: T) => {
let fns: Array<(x: any) => unknown> = [];
let cached: { v: T } | undefined = undefined;
const self = {
to: <U>(f: (v: T) => U) => {
fns.push((x: T) => f(x));
return self as unknown as ReturnType<typeof pipe<U>>;
},
run: (): T => {
if (cached) return cached.v;
let v: any = value;
switch (fns.length) {
case 0: break;
case 1: v = fns[0](v); break;
case 2: v = fns[1](fns[0](v)); break;
case 3: v = fns[2](fns[1](fns[0](v))); break;
default: for (const fn of fns) v = fn(v); break;
}
cached = { v };
return v;
}
}
return self;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment