yield-stream
Advanced tools
Comparing version 1.0.4 to 1.0.5
{ | ||
"name": "yield-stream", | ||
"version": "1.0.4", | ||
"version": "1.0.5", | ||
"license": "MIT", | ||
@@ -5,0 +5,0 @@ "type": "module", |
@@ -9,11 +9,11 @@ # `yield-stream` | ||
```ts | ||
import { GeneratorFn, StreamGenerator } from "./types"; | ||
/** | ||
* `compose(f, g, h, ...)` returns a generator function `G(data)` that yields | ||
* all `(f · g · h · ...)(data)`. | ||
* | ||
* @note Used to compose multiple transforms into a `pipeline`. | ||
*/ | ||
export const compose = <T>( | ||
...generators: GeneratorFn<T>[] | ||
) => { | ||
): GeneratorFn<T> => { | ||
return generators.reduce( | ||
@@ -29,3 +29,4 @@ (prev, next) => async function* (data) { | ||
/** | ||
* Runs each chunk through all of the given transforms. | ||
* Accepts a stream and transforms and returns a stream of the transformed | ||
* chunks. Transforms can yield multiple chunks per input chunk. | ||
*/ | ||
@@ -35,3 +36,3 @@ export const pipeline = <T>( | ||
...transforms: GeneratorFn<T>[] | ||
) => { | ||
): ReadableStream<T> => { | ||
const composed = compose(...transforms); | ||
@@ -48,3 +49,3 @@ return generateStream( | ||
/** | ||
* Iterates over a stream, yielding each chunk. | ||
* Accepts a stream and yields all of its chunks. | ||
*/ | ||
@@ -71,3 +72,3 @@ export const yieldStream = async function* <T>( | ||
/** | ||
* Creates a ReadableStream from a generator function. | ||
* Accepts a generator function and streams its outputs. | ||
*/ | ||
@@ -77,3 +78,3 @@ export const generateStream = <T, TReturn, D>( | ||
data?: D | ||
) => { | ||
): ReadableStream<T> => { | ||
return new ReadableStream<T>({ | ||
@@ -90,5 +91,5 @@ async start(controller) { | ||
/** | ||
* Creates a ReadableStream that yields all values in an array. | ||
* Accepts an array and returns a stream of its items. | ||
*/ | ||
export const streamArray = <T>(array: T[]) => { | ||
export const streamArray = <T>(array: T[]): ReadableStream<T> => { | ||
return generateStream(function* () { | ||
@@ -100,2 +101,14 @@ for (const item of array) { | ||
}; | ||
/** | ||
* Accepts a stream and yields a growing buffer of all chunks received. | ||
*/ | ||
export const buffer = async function* <T>(stream: ReadableStream<T>) { | ||
const buffer: T[] = []; | ||
for await (const chunk of yieldStream(stream)) { | ||
buffer.push(chunk); | ||
yield buffer; | ||
} | ||
}; | ||
``` |
6924
106