Created
August 9, 2022 15:01
-
-
Save phunanon/dc29c15f78074a4db312c803654952a9 to your computer and use it in GitHub Desktop.
Strongly types a pipeline of functions.
This file contains 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 = | |
<Ctx, Ingress, A, B, C, Egress>( | |
...args: | |
| [(x: Ingress, ctx: Ctx) => Promise<Egress>] | |
| [ | |
(x: Ingress, ctx: Ctx) => Promise<A>, | |
(x: A, ctx: Ctx) => Promise<Egress> | |
] | |
| [ | |
(x: Ingress, ctx: Ctx) => Promise<A>, | |
(x: A, ctx: Ctx) => Promise<B>, | |
(x: B, ctx: Ctx) => Promise<Egress> | |
] | |
| [ | |
(x: Ingress, ctx: Ctx) => Promise<A>, | |
(x: A, ctx: Ctx) => Promise<B>, | |
(x: B, ctx: Ctx) => Promise<C>, | |
(x: C, ctx: Ctx) => Promise<Egress> | |
] | |
) => | |
async (context: Ctx, ingress: Ingress) => { | |
let data: any = ingress; | |
for (const effect of args) { | |
data = await effect(data, context); | |
} | |
return <Egress>data; | |
}; | |
async function myTest() { | |
const affect = pipe( | |
async (x: string, ctx: string) => x + ctx, | |
async (x: string, ctx: string) => x + ctx, | |
async (x: string, ctx: string) => Number(x + ctx) | |
); | |
const ctx = "hello"; | |
const data = "hi"; | |
const egress = await affect(ctx, data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A crazier version: