Created
May 27, 2026 14:37
-
-
Save trvswgnr/56b4d2c71234bbfb2db19b38b80919d6 to your computer and use it in GitHub Desktop.
ts simplest lazy pipe
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
| 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