import { AsyncIterableX } from '../asynciterablex.js'; import { OperatorAsyncFunction } from '../../interfaces.js'; import { wrapWithAbort } from './withabort.js'; import { throwIfAborted } from '../../aborterror.js'; /** @ignore */ export class FilterAsyncIterable extends AsyncIterableX { private _source: AsyncIterable; private _predicate: (value: TSource, index: number) => boolean | Promise; private _thisArg: any; constructor( source: AsyncIterable, predicate: (value: TSource, index: number) => boolean | Promise, thisArg?: any ) { super(); this._source = source; this._predicate = predicate; this._thisArg = thisArg; } async *[Symbol.asyncIterator](signal?: AbortSignal) { throwIfAborted(signal); let i = 0; for await (const item of wrapWithAbort(this._source, signal)) { if (await this._predicate.call(this._thisArg, item, i++)) { yield item; } } } } export function filter( predicate: (value: T, index: number) => value is S, thisArg?: any ): OperatorAsyncFunction; export function filter( predicate: (value: T, index: number) => boolean | Promise, thisArg?: any ): OperatorAsyncFunction; /** * Filters the elements of an async-iterable sequence based on a predicate. * * @template TSource The type of the elements in the source sequence. * @param {((value: TSource, index: number, signal?: AbortSignal) => boolean | Promise)} predicate A function to test each source element * for a condition. * @param {*} [thisArg] Optional this for binding. * @returns {OperatorAsyncFunction} An operator which returns an async-iterable * sequence that contains elements from the input sequence that satisfy the condition. */ export function filter( predicate: (value: TSource, index: number, signal?: AbortSignal) => boolean | Promise, thisArg?: any ): OperatorAsyncFunction { return function filterOperatorFunction(source: AsyncIterable): AsyncIterableX { return new FilterAsyncIterable(source, predicate, thisArg); }; }