import { AsyncIterableX } from '../asynciterablex.js'; import { identityAsync } from '../../util/identity.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 DistinctUntilChangedAsyncIterable extends AsyncIterableX< TSource > { 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: (first: TKey, second: TKey) => boolean | Promise ) { super(); this._source = source; this._keySelector = keySelector; this._comparer = comparer; } async *[Symbol.asyncIterator](signal?: AbortSignal) { throwIfAborted(signal); let currentKey: TKey | undefined; let hasCurrentKey = false; for await (const item of wrapWithAbort(this._source, signal)) { const key = await this._keySelector(item, signal); let comparerEquals = false; if (hasCurrentKey) { comparerEquals = await this._comparer(currentKey!, key); } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; yield item; } } } } /** * Returns an async-iterable sequence that contains only distinct contiguous elements according to the optional 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 options for adding a key selector and comparer. * @returns {MonoTypeOperatorAsyncFunction} An operator that returns an async-iterable that contains only distinct contiguous items. */ export function distinctUntilChanged( options?: DistinctOptions ): MonoTypeOperatorAsyncFunction { return function distinctUntilChangedOperatorFunction( source: AsyncIterable ): AsyncIterableX { const { ['keySelector']: keySelector = identityAsync, ['comparer']: comparer = comparerAsync } = options || {}; return new DistinctUntilChangedAsyncIterable(source, keySelector, comparer); }; }