import { IterableX } from '../iterablex.js'; import { identity } from '../../util/identity.js'; import { comparer as defaultComparer } from '../../util/comparer.js'; import { MonoTypeOperatorFunction } from '../../interfaces.js'; import { DistinctOptions } from './distinctoptions.js'; /** @ignore */ export class DistinctUntilChangedIterable extends IterableX { private _source: Iterable; private _keySelector: (value: TSource) => TKey; private _comparer: (x: TKey, y: TKey) => boolean; constructor( source: Iterable, keySelector: (value: TSource) => TKey, comparer: (first: TKey, second: TKey) => boolean ) { super(); this._source = source; this._keySelector = keySelector; this._comparer = comparer; } *[Symbol.iterator]() { let currentKey = {}; let hasCurrentKey = false; for (const item of this._source) { const key = this._keySelector(item); let comparerEquals = false; if (hasCurrentKey) { comparerEquals = 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 {MonoTypeOperatorFunction} An operator that returns an async-iterable that contains only distinct contiguous items. */ export function distinctUntilChanged( options?: DistinctOptions ): MonoTypeOperatorFunction { return function distinctUntilChangedOperatorFunction( source: Iterable ): IterableX { const { ['keySelector']: keySelector = identity, ['comparer']: comparer = defaultComparer } = options || {}; return new DistinctUntilChangedIterable(source, keySelector!, comparer!); }; }