@johngw/stream
Version:
Reactive programming tools using the WHATWG Streams API.
47 lines • 1.48 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.flat = void 0;
const Object_1 = require("@johngw/stream-common/Object");
/**
* Deeply flattens `Iterable`s, `AsyncIterable`s & `ArrayLike`s.
*
* @group Transformers
* @example
* ```
* --[1]--2----[3,[4]]---|
*
* flat()
*
* --1----2-----3-4------|
* ```
*/
function flat() {
return new TransformStream(new FlatTransformer());
}
exports.flat = flat;
class FlatTransformer {
transform(chunk, controller) {
return typeof chunk === 'string'
? controller.enqueue(chunk)
: (0, Object_1.isIterable)(chunk)
? this.#transformIterator(chunk, controller)
: (0, Object_1.isAsyncIterable)(chunk)
? this.#transformAsyncIterator(chunk, controller)
: (0, Object_1.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