feat(async/unstable): accept iterator varargs in MuxAsyncIterator (#6087)

Co-authored-by: Yoshiya Hinosawa <stibium121@gmail.com>
This commit is contained in:
scarf 2024-10-08 23:20:01 +09:00 committed by GitHub
parent acee24ac0c
commit c221924aec
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 73 additions and 0 deletions

View File

@ -8,6 +8,7 @@
"./debounce": "./debounce.ts", "./debounce": "./debounce.ts",
"./delay": "./delay.ts", "./delay": "./delay.ts",
"./mux-async-iterator": "./mux_async_iterator.ts", "./mux-async-iterator": "./mux_async_iterator.ts",
"./unstable-mux-async-iterator": "./unstable_mux_async_iterator.ts",
"./pool": "./pool.ts", "./pool": "./pool.ts",
"./retry": "./retry.ts", "./retry": "./retry.ts",
"./tee": "./tee.ts" "./tee": "./tee.ts"

View File

@ -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<number> {
* yield 1;
* yield 2;
* yield 3;
* }
*
* async function* gen456(): AsyncIterableIterator<number> {
* 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<T> extends MaxAsyncIterator_<T> {
/**
* Constructs a new {@linkcode MuxAsyncIterator} instance.
*
* @param iterables The async iterables to multiplex.
*/
constructor(...iterables: AsyncIterable<T>[]) {
super();
for (const iterable of iterables) this.add(iterable);
}
}

View File

@ -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<number> {
yield 1;
yield 2;
yield 3;
}
async function* gen456(): AsyncIterableIterator<number> {
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]));
});