import { AsyncIterableX } from '../asynciterablex.js'; import { arrayIndexOfAsync } from '../../util/arrayindexof.js'; import { comparerAsync } from '../../util/comparer.js'; import { MonoTypeOperatorAsyncFunction } from '../../interfaces.js'; import { wrapWithAbort } from './withabort.js'; import { throwIfAborted } from '../../aborterror.js'; /** @ignore */ export class UnionAsyncIterable extends AsyncIterableX { private _left: AsyncIterable; private _right: AsyncIterable; private _comparer: (x: TSource, y: TSource) => boolean | Promise; constructor( left: AsyncIterable, right: AsyncIterable, comparer: (x: TSource, y: TSource) => boolean | Promise ) { super(); this._left = left; this._right = right; this._comparer = comparer; } async *[Symbol.asyncIterator](signal?: AbortSignal) { throwIfAborted(signal); const map = [] as TSource[]; for await (const lItem of wrapWithAbort(this._left, signal)) { if ((await arrayIndexOfAsync(map, lItem, this._comparer)) === -1) { map.push(lItem); yield lItem; } } for await (const rItem of wrapWithAbort(this._right, signal)) { if ((await arrayIndexOfAsync(map, rItem, this._comparer)) === -1) { map.push(rItem); yield rItem; } } } } /** * Produces the set union of two sequences by using the given equality comparer. * * @template TSource The type of the elements of the input sequences. * @param {AsyncIterable} right An async-iterable sequence whose distinct elements form the second set for the union. * @param {((x: TSource, y: TSource) => boolean | Promise)} [comparer=comparerAsync] The equality comparer to compare values. * @returns {MonoTypeOperatorAsyncFunction} An async-iterable sequence that contains the elements from both input sequences, * excluding duplicates. */ export function union( right: AsyncIterable, comparer: (x: TSource, y: TSource) => boolean | Promise = comparerAsync ): MonoTypeOperatorAsyncFunction { return function unionOperatorFunction(left: AsyncIterable): AsyncIterableX { return new UnionAsyncIterable(left, right, comparer); }; }