@johngw/stream
Version:
Reactive programming tools using the WHATWG Streams API.
43 lines • 1.36 kB
JavaScript
import { isArrayLike, isAsyncIterable, isIterable, } from '@johngw/stream-common/Object';
/**
* Deeply flattens `Iterable`s, `AsyncIterable`s & `ArrayLike`s.
*
* @group Transformers
* @example
* ```
* --[1]--2----[3,[4]]---|
*
* flat()
*
* --1----2-----3-4------|
* ```
*/
export function flat() {
return new TransformStream(new FlatTransformer());
}
class FlatTransformer {
transform(chunk, controller) {
return typeof chunk === 'string'
? controller.enqueue(chunk)
: isIterable(chunk)
? this.#transformIterator(chunk, controller)
: isAsyncIterable(chunk)
? this.#transformAsyncIterator(chunk, controller)
: isArrayLike(chunk)
? this.#transformArrayLike(chunk, controller)
: controller.enqueue(chunk);
}
async #transformIterator(chunk, controller) {
for (const x of chunk)
await this.transform(x, controller);
}
async #transformAsyncIterator(chunk, controller) {
for await (const x of chunk)
await this.transform(x, controller);
}
async #transformArrayLike(chunk, controller) {
for (let i = 0; i < chunk.length; i++)
await this.transform(chunk[i], controller);
}
}
//# sourceMappingURL=flat.js.map