From 1041655b289936a33e1108d498165a93d5e4e94e Mon Sep 17 00:00:00 2001 From: "Afshin T. Darian" Date: Thu, 11 Aug 2022 16:08:54 +0100 Subject: [PATCH] Reimplement filter() with native interators --- packages/algorithm/src/filter.ts | 74 +++++--------------------------- 1 file changed, 10 insertions(+), 64 deletions(-) diff --git a/packages/algorithm/src/filter.ts b/packages/algorithm/src/filter.ts index 0c85ba9bf..2eee493f9 100644 --- a/packages/algorithm/src/filter.ts +++ b/packages/algorithm/src/filter.ts @@ -7,12 +7,11 @@ | | The full license is in the file LICENSE, distributed with this software. |----------------------------------------------------------------------------*/ -import { IIterator, iter, IterableOrArrayLike } from './iter'; /** * Filter an iterable for values which pass a test. * - * @param object - The iterable or array-like object of interest. + * @param object - The iterable object of interest. * * @param fn - The predicate function to invoke for each value. * @@ -20,76 +19,23 @@ import { IIterator, iter, IterableOrArrayLike } from './iter'; * * #### Example * ```typescript - * import { filter, toArray } from '@lumino/algorithm'; + * import { filter } from '@lumino/algorithm'; * * let data = [1, 2, 3, 4, 5, 6]; * * let stream = filter(data, value => value % 2 === 0); * - * toArray(stream); // [2, 4, 6] + * Array.from(stream); // [2, 4, 6] * ``` */ -export function filter( - object: IterableOrArrayLike, +export function* filter( + object: Iterable, fn: (value: T, index: number) => boolean -): IIterator { - return new FilterIterator(iter(object), fn); -} - -/** - * An iterator which yields values which pass a test. - */ -export class FilterIterator implements IIterator { - /** - * Construct a new filter iterator. - * - * @param source - The iterator of values of interest. - * - * @param fn - The predicate function to invoke for each value. - */ - constructor(source: IIterator, fn: (value: T, index: number) => boolean) { - this._source = source; - this._fn = fn; - } - - /** - * Get an iterator over the object's values. - * - * @returns An iterator which yields the object's values. - */ - iter(): IIterator { - return this; - } - - /** - * Create an independent clone of the iterator. - * - * @returns A new independent clone of the iterator. - */ - clone(): IIterator { - let result = new FilterIterator(this._source.clone(), this._fn); - result._index = this._index; - return result; - } - - /** - * Get the next value from the iterator. - * - * @returns The next value from the iterator, or `undefined`. - */ - next(): T | undefined { - let fn = this._fn; - let it = this._source; - let value: T | undefined; - while ((value = it.next()) !== undefined) { - if (fn(value, this._index++)) { - return value; - } +) { + let index = 0; + for (const value of object) { + if (fn(value, index++)) { + yield value; } - return undefined; } - - private _index = 0; - private _source: IIterator; - private _fn: (value: T, index: number) => boolean; }