-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
}, | ||
}); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
}); |