2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2023-03-18 12:36:00 +00:00
|
|
|
// This module is browser compatible.
|
2022-11-29 13:55:38 +00:00
|
|
|
|
|
|
|
/**
|
2023-12-04 06:12:52 +00:00
|
|
|
* Merge multiple streams into a single one, taking order into account, and
|
|
|
|
* each stream will wait for a chunk to enqueue before the next stream can
|
|
|
|
* append another chunk. If a stream ends before other ones, the others will
|
|
|
|
* continue adding data in order, and the finished one will not add any more
|
|
|
|
* data.
|
|
|
|
*
|
|
|
|
* @example
|
|
|
|
* ```ts
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { zipReadableStreams } from "@std/streams/zip-readable-streams";
|
2023-12-04 06:12:52 +00:00
|
|
|
*
|
|
|
|
* const stream1 = ReadableStream.from(["1", "2", "3"]);
|
|
|
|
* const stream2 = ReadableStream.from(["a", "b", "c"]);
|
|
|
|
* const zippedStream = zipReadableStreams(stream1, stream2);
|
|
|
|
*
|
|
|
|
* await Array.fromAsync(zippedStream); // ["1", "a", "2", "b", "3", "c"];
|
|
|
|
* ```
|
2022-11-29 13:55:38 +00:00
|
|
|
*/
|
|
|
|
export function zipReadableStreams<T>(
|
|
|
|
...streams: ReadableStream<T>[]
|
|
|
|
): ReadableStream<T> {
|
2023-09-21 10:23:28 +00:00
|
|
|
const readers = new Set(streams.map((s) => s.getReader()));
|
2022-11-29 13:55:38 +00:00
|
|
|
return new ReadableStream<T>({
|
|
|
|
async start(controller) {
|
|
|
|
try {
|
|
|
|
let resolved = 0;
|
2023-08-25 09:04:43 +00:00
|
|
|
while (resolved !== streams.length) {
|
2023-09-21 10:23:28 +00:00
|
|
|
for (const reader of readers) {
|
2022-11-29 13:55:38 +00:00
|
|
|
const { value, done } = await reader.read();
|
|
|
|
if (!done) {
|
|
|
|
controller.enqueue(value!);
|
|
|
|
} else {
|
|
|
|
resolved++;
|
2023-09-21 10:23:28 +00:00
|
|
|
readers.delete(reader);
|
2022-11-29 13:55:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
controller.close();
|
|
|
|
} catch (e) {
|
|
|
|
controller.error(e);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|