From 8c3b2c09006c8fdbf9e124978aafb47543a19850 Mon Sep 17 00:00:00 2001 From: "Afshin T. Darian" Date: Thu, 11 Aug 2022 16:19:41 +0100 Subject: [PATCH] Reimplement map() with native interators --- packages/algorithm/src/map.ts | 71 +++++------------------------------ 1 file changed, 9 insertions(+), 62 deletions(-) diff --git a/packages/algorithm/src/map.ts b/packages/algorithm/src/map.ts index 6a8cd4cc7..575416993 100644 --- a/packages/algorithm/src/map.ts +++ b/packages/algorithm/src/map.ts @@ -7,12 +7,10 @@ | | The full license is in the file LICENSE, distributed with this software. |----------------------------------------------------------------------------*/ -import { IIterator, iter, IterableOrArrayLike } from './iter'; - /** * Transform the values of an iterable with a mapping function. * - * @param object - The iterable or array-like object of interest. + * @param object - The iterable object of interest. * * @param fn - The mapping function to invoke for each value. * @@ -20,72 +18,21 @@ import { IIterator, iter, IterableOrArrayLike } from './iter'; * * #### Example * ```typescript - * import { map, toArray } from '@lumino/algorithm'; + * import { map } from '@lumino/algorithm'; * * let data = [1, 2, 3]; * * let stream = map(data, value => value * 2); * - * toArray(stream); // [2, 4, 6] + * Array.from(stream); // [2, 4, 6] * ``` */ -export function map( - object: IterableOrArrayLike, +export function* map( + object: Iterable, fn: (value: T, index: number) => U -): IIterator { - return new MapIterator(iter(object), fn); -} - -/** - * An iterator which transforms values using a mapping function. - */ -export class MapIterator implements IIterator { - /** - * Construct a new map iterator. - * - * @param source - The iterator of values of interest. - * - * @param fn - The mapping function to invoke for each value. - */ - constructor(source: IIterator, fn: (value: T, index: number) => U) { - 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 MapIterator(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(): U | undefined { - let value = this._source.next(); - if (value === undefined) { - return undefined; - } - return this._fn.call(undefined, value, this._index++); +) { + let index = 0; + for (const value of object) { + yield fn(value, index++); } - - private _index = 0; - private _source: IIterator; - private _fn: (value: T, index: number) => U; }