Skip to content

Commit

Permalink
feat: merge
Browse files Browse the repository at this point in the history
  • Loading branch information
ilteoood committed Dec 1, 2023
1 parent b0207ea commit aea3612
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/merge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const recursivePromiseBuilder = <T>(reader: ReadableStreamDefaultReader<T>, controller: ReadableStreamDefaultController<T>) => {
const recursivePromise = async () => {
const readResult = await reader.read();

if (!readResult.done) {
controller.enqueue(readResult.value);

return recursivePromise();
}

}

return recursivePromise();
}

export const merge = <T>(...readableStreams: ReadableStream<T>[]) => {
const fallbackedStreams = readableStreams ?? [];

return new ReadableStream<T>({
async pull(controller) {

await Promise.all(
fallbackedStreams.map(stream => recursivePromiseBuilder(stream.getReader(), controller))
)

controller.close();
},
});
};
33 changes: 33 additions & 0 deletions test/merge.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { describe, expect, test } from "vitest";

import { fromIterable } from "../src/fromIterable";
import { merge } from "../src/merge";
import { pipeline } from "../src/pipeline";
import { toArray } from "../src/toArray";

describe("merge", () => {
test("should merge streams", async () => {
const destinationArray = [];

await pipeline(
merge(fromIterable([1]), fromIterable([2]), fromIterable([3])),
toArray(destinationArray),
);

expect(destinationArray).toContain(1);
expect(destinationArray).toContain(2);
expect(destinationArray).toContain(3);
});

test("should merge streams even if first stream is empty", async () => {
const destinationArray = [];

await pipeline(
merge(fromIterable([]), fromIterable([2]), fromIterable([3])),
toArray(destinationArray),
);

expect(destinationArray).toContain(2);
expect(destinationArray).toContain(3);
});
});

0 comments on commit aea3612

Please sign in to comment.