ix
Version:
The Interactive Extensions for JavaScript
54 lines (52 loc) • 2.04 kB
JavaScript
import { __asyncGenerator, __await } from "tslib";
import { AsyncIterableX } from './asynciterablex.mjs';
import { wrapWithAbort } from './operators/withabort.mjs';
import { throwIfAborted } from '../aborterror.mjs';
import { safeRace } from '../util/safeRace.mjs';
// eslint-disable-next-line @typescript-eslint/no-empty-function
const NEVER_PROMISE = new Promise(() => { });
function wrapPromiseWithIndex(promise, index) {
return promise
.then(({ value, done }) => ({ value, done, index }))
.catch((error) => ({ error, index }));
}
/** @ignore */
export class MergeAsyncIterable extends AsyncIterableX {
constructor(source) {
super();
this._source = source;
}
[Symbol.asyncIterator](signal) {
return __asyncGenerator(this, arguments, function* _a() {
throwIfAborted(signal);
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 = wrapWithAbort(this._source[i], signal)[Symbol.asyncIterator]();
iterators[i] = iterator;
nexts[i] = wrapPromiseWithIndex(iterator.next(), i);
}
while (active > 0) {
const next = yield __await(safeRace(nexts));
if (next.hasOwnProperty('error')) {
throw next.error;
}
else if (next.done) {
nexts[next.index] = NEVER_PROMISE;
active--;
}
else {
const iterator$ = iterators[next.index];
nexts[next.index] = wrapPromiseWithIndex(iterator$.next(), next.index);
yield yield __await(next.value);
}
}
});
}
}
export function merge(source, ...args) {
return new MergeAsyncIterable([source, ...args]);
}
//# sourceMappingURL=merge.mjs.map