Async Generator Pipeline Compose (JavaScript)
Compose async generators into a pipeline for lazy streaming transformation with backpressure.
Code
export async function* pipe(source,...transforms){let current=source;for(const transform of transforms){current=transform(current);}yield* current;}export function map(fn){return async function*(iter){for await(const item of iter)yield fn(item);};}export function filter(pred){return async function*(iter){for await(const item of iter)if(pred(item))yield item;};}export function take(n){return async function*(iter){let i=0;for await(const item of iter){if(i++>=n)return;yield item;}};}export function batch(size){return async function*(iter){let buf=[];for await(const item of iter){buf.push(item);if(buf.length>=size){yield buf;buf=[];}}if(buf.length>0)yield buf;};}How it works
Async Generator Pipeline Compose (JavaScript) keeps everything in the functions map, filter, take and batch.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
What to watch for
- The guard
i++>=nshort-circuits the flow with an earlyreturnwhen its condition holds.
Where you would put it to use
The main signature reads export async function* pipe(source,...transforms)
Import pipe from the file and call it — the rest of the code is implementation detail.
Interactive Tools for This Topic
FAQ
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. The file defines `map`, `filter`, `take` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.