UNPKG

@reactivex/ix-esnext-esm

Version:

The Interactive Extensions for JavaScript

45 lines (43 loc) 1.5 kB
import { AsyncIterableX } from './asynciterablex'; // eslint-disable-next-line @typescript-eslint/no-empty-function const NEVER_PROMISE = new Promise(() => { }); function wrapPromiseWithIndex(promise, index) { return promise.then(value => ({ value, index })); } export class MergeAsyncIterable extends AsyncIterableX { constructor(source) { super(); this._source = source; } async *[Symbol.asyncIterator]() { const length = this._source.length; const iterators = new Array(length); const nexts = new Array(length); let active = length; for (let i = 0; i < length; i++) { const iterator = this._source[i][Symbol.asyncIterator](); iterators[i] = iterator; nexts[i] = wrapPromiseWithIndex(iterator.next(), i); } while (active > 0) { const next = Promise.race(nexts); const { value: next$, index } = await next; if (next$.done) { nexts[index] = NEVER_PROMISE; active--; } else { const iterator$ = iterators[index]; nexts[index] = wrapPromiseWithIndex(iterator$.next(), index); yield next$.value; } } } } export function merge(source, ...args) { return new MergeAsyncIterable([source, ...args]); } export function mergeStatic(...args) { return new MergeAsyncIterable(args); } //# sourceMappingURL=merge.mjs.map