UNPKG

asyncreiterable

Version:

An AsyncReiterable is an append-only collection that allows multiple asynchronous iterations.

73 lines 2.65 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AsyncReiterableArray = void 0; const asynciterator_1 = require("asynciterator"); /** * An {@link AsyncReiterable} that is backed by an array. */ class AsyncReiterableArray { constructor(array, terminate) { this.array = array.slice(); this.iterators = []; if (terminate) { this.array.push(null); } } /** * Create a new {@link AsyncReiterableArray} with the given data elements * that will be ended. * @param {T[]} array An array of data elements. * @return {AsyncReiterableArray<T>} A new ended {@link AsyncReiterableArray} with the given data elements. */ static fromFixedData(array) { return new AsyncReiterableArray(array, true); } /** * Create a new {@link AsyncReiterableArray} with the given data elements * that will not be ended. * @param {T[]} initialData An array of initial data elements. * @return {AsyncReiterableArray<T>} A new open-ended {@link AsyncReiterableArray} with the given data elements. */ static fromInitialData(initialData) { return new AsyncReiterableArray(initialData, false); } /** * @return {AsyncReiterableArray<T>} A new open-ended {@link AsyncReiterableArray} without data elements. */ static fromInitialEmpty() { return AsyncReiterableArray.fromInitialData([]); } static pushToIterator(iterator, data) { if (data === null) { iterator.close(); } else { iterator._push(data); // Beware: this is a hack } } iterator() { if (this.isEnded()) { return new asynciterator_1.ArrayIterator(this.array.slice(0, this.array.length - 1), { autoStart: false }); } const iterator = new asynciterator_1.BufferedIterator({ autoStart: false }); for (const data of this.array) { AsyncReiterableArray.pushToIterator(iterator, data); } this.iterators.push(iterator); return iterator; } push(data) { if (this.isEnded()) { throw new Error('Can not push data anymore into an AsyncReiterableArray after it has been terminated.'); } this.array.push(data); for (const iterator of this.iterators) { AsyncReiterableArray.pushToIterator(iterator, data); } } isEnded() { return this.array.length > 0 && this.array[this.array.length - 1] === null; } } exports.AsyncReiterableArray = AsyncReiterableArray; //# sourceMappingURL=AsyncReiterableArray.js.map