UNPKG

@johngw/stream

Version:

Reactive programming tools using the WHATWG Streams API.

115 lines 2.98 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ArrayLikeSource = exports.IteratorSource = exports.fromCollection = void 0; const assert_never_1 = require("assert-never"); const Object_1 = require("@johngw/stream-common/Object"); /** * Creates a readable stream from an collection of values. * * @group Sources * @example * Using an iterable * ``` * fromCollection([1, 2, 3, 4]) * ``` * * Using an Async Iterable * ``` * fromCollection((async function* () { * yield 1 * })()) * ``` * * Using an ArrayLike * ``` * fromCollection({ * 0: 'zero', * 1: 'one', * 2: 'two', * length: 3, * }) * ``` */ function fromCollection(collection, queuingStrategy) { return new ReadableStream((0, Object_1.isIterable)(collection) ? new IteratorSource(collection[Symbol.iterator]()) : (0, Object_1.isAsyncIterable)(collection) ? new IteratorSource(collection[Symbol.asyncIterator]()) : (0, Object_1.isIteratorOrAsyncIterator)(collection) ? new IteratorSource(collection) : (0, Object_1.isArrayLike)(collection) ? new ArrayLikeSource(collection) : (0, assert_never_1.assertNever)(collection), queuingStrategy); } exports.fromCollection = fromCollection; /** * An underlying source for an `Iterator` or `AsyncIterator`. * * @group Sources * @example * ``` * const reader = new ReadableStream(new IteratorSource((function* () { * yield 1 * yield 2 * })())) * ``` */ class IteratorSource { #iterator; constructor(iterator) { this.#iterator = iterator; } async pull(controller) { while (controller.desiredSize) { let result; try { result = await this.#iterator.next(); } catch (error) { return controller.error(error); } if (result.done) return controller.close(); else controller.enqueue(result.value); } } } exports.IteratorSource = IteratorSource; /** * An underlying source for an `ArrayLike`. * * @group Sources * @example * ``` * const reader = new ReadableStream(new ArrayLikeSource({ * 0: 'zero', * 1: 'one', * length: 2 * })) * ``` */ class ArrayLikeSource { #arrayLike; #length; #i = 0; constructor(arrayLike) { this.#arrayLike = arrayLike; this.#length = arrayLike.length; } start(controller) { if (this.#finished) controller.close(); } pull(controller) { for (; controller.desiredSize && this.#i < this.#length; this.#i++) controller.enqueue(this.#arrayLike[this.#i]); if (this.#finished) controller.close(); } get #finished() { return this.#i === this.#length; } } exports.ArrayLikeSource = ArrayLikeSource; //# sourceMappingURL=fromCollection.js.map