diff --git a/async/deno.json b/async/deno.json index c2c5e4ad8..b3cdcd23c 100644 --- a/async/deno.json +++ b/async/deno.json @@ -8,6 +8,7 @@ "./debounce": "./debounce.ts", "./delay": "./delay.ts", "./mux-async-iterator": "./mux_async_iterator.ts", + "./unstable-mux-async-iterator": "./unstable_mux_async_iterator.ts", "./pool": "./pool.ts", "./retry": "./retry.ts", "./tee": "./tee.ts" diff --git a/async/unstable_mux_async_iterator.ts b/async/unstable_mux_async_iterator.ts new file mode 100644 index 000000000..3cc157ce7 --- /dev/null +++ b/async/unstable_mux_async_iterator.ts @@ -0,0 +1,50 @@ +// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. +// This module is browser compatible. + +import { MuxAsyncIterator as MaxAsyncIterator_ } from "./mux_async_iterator.ts"; + +/** + * Multiplexes multiple async iterators into a single stream. It currently + * makes an assumption that the final result (the value returned and not + * yielded from the iterator) does not matter; if there is any result, it is + * discarded. + * + * @experimental **UNSTABLE**: New API, yet to be vetted. + * + * @example Usage + * ```ts + * import { MuxAsyncIterator } from "@std/async/unstable-mux-async-iterator"; + * import { assertEquals } from "@std/assert"; + * + * async function* gen123(): AsyncIterableIterator { + * yield 1; + * yield 2; + * yield 3; + * } + * + * async function* gen456(): AsyncIterableIterator { + * yield 4; + * yield 5; + * yield 6; + * } + * + * const mux = new MuxAsyncIterator(gen123(), gen456()); + * + * const result = await Array.fromAsync(mux); + * + * assertEquals(result, [1, 4, 2, 5, 3, 6]); + * ``` + * + * @typeParam T The type of the provided async iterables and generated async iterable. + */ +export class MuxAsyncIterator extends MaxAsyncIterator_ { + /** + * Constructs a new {@linkcode MuxAsyncIterator} instance. + * + * @param iterables The async iterables to multiplex. + */ + constructor(...iterables: AsyncIterable[]) { + super(); + for (const iterable of iterables) this.add(iterable); + } +} diff --git a/async/unstable_mux_async_iterator_test.ts b/async/unstable_mux_async_iterator_test.ts new file mode 100644 index 000000000..ada1cbae3 --- /dev/null +++ b/async/unstable_mux_async_iterator_test.ts @@ -0,0 +1,22 @@ +// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. +import { assertEquals } from "@std/assert"; +import { MuxAsyncIterator } from "./unstable_mux_async_iterator.ts"; + +async function* gen123(): AsyncIterableIterator { + yield 1; + yield 2; + yield 3; +} + +async function* gen456(): AsyncIterableIterator { + yield 4; + yield 5; + yield 6; +} + +Deno.test("(unstable) MuxAsyncIterator() works with constructor iterables", async () => { + const mux = new MuxAsyncIterator(gen123(), gen456()); + const results = new Set(await Array.fromAsync(mux)); + assertEquals(results.size, 6); + assertEquals(results, new Set([1, 4, 2, 5, 3, 6])); +});