import { AsyncIterableX } from './../asynciterablex.js'; import { identityAsync } from '../../util/identity.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'; import { DistinctOptions } from './distinctoptions.js'; /** @ignore */ export class DistinctAsyncIterable extends AsyncIterableX { private _source: AsyncIterable; private _keySelector: (value: TSource, signal?: AbortSignal) => TKey | Promise; private _comparer: (x: TKey, y: TKey) => boolean | Promise; constructor( source: AsyncIterable, keySelector: (value: TSource, signal?: AbortSignal) => TKey | Promise, comparer: (x: TKey, y: TKey) => boolean | Promise ) { super(); this._source = source; this._keySelector = keySelector; this._comparer = comparer; } async *[Symbol.asyncIterator](signal?: AbortSignal) { throwIfAborted(signal); const set = [] as TKey[]; for await (const item of wrapWithAbort(this._source, signal)) { const key = await this._keySelector(item, signal); if ((await arrayIndexOfAsync(set, key, this._comparer)) === -1) { set.push(key); yield item; } } } } /** * Returns an async-iterable sequence that contains only distinct elements according to the keySelector and comparer. * * @template TSource The type of the elements in the source sequence. * @template TKey The type of the discriminator key computed for each element in the source sequence. * @param {DistinctOptions} [options] The optional arguments for a key selector and comparer function. * @returns {MonoTypeOperatorAsyncFunction} An operator that returns distinct elements according to the keySelector and options. */ export function distinct( options?: DistinctOptions ): MonoTypeOperatorAsyncFunction { return function distinctOperatorFunction( source: AsyncIterable ): AsyncIterableX { const { ['keySelector']: keySelector = identityAsync, ['comparer']: comparer = comparerAsync } = options || {}; return new DistinctAsyncIterable(source, keySelector, comparer); }; }