-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
provide.ts
36 lines (36 loc) · 1.05 KB
/
provide.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Provides the given values to the writable stream by piping them from a readable stream
* created from the values. Returns a promise that resolves when all the values have been
* successfully written to the stream.
*
* ```ts
* import { provide } from "@core/streamutil/provide";
*
* const results: number[] = [];
* const writer = new WritableStream<number>({
* write(chunk) {
* results.push(chunk);
* },
* });
*
* await provide(writer, [1, 2, 3]);
* console.log(results); // [1, 2, 3]
* ```
*
* @param stream The writable stream to write the values to.
* @param values An array of values to write to the stream.
* @returns A promise that resolves when all values have been successfully written to the stream.
*/
export async function provide<T>(
stream: WritableStream<T>,
values: T[],
options: StreamPipeOptions = {},
): Promise<void> {
const input = new ReadableStream({
start(controller) {
values.forEach((value) => controller.enqueue(value));
controller.close();
},
});
await input.pipeTo(stream, options);
}