UNPKG

2.46 kBPlain TextView Raw
1// Copyright (c) Jupyter Development Team.
2// Distributed under the terms of the Modified BSD License.
3/*-----------------------------------------------------------------------------
4| Copyright (c) 2014-2017, PhosphorJS Contributors
5|
6| Distributed under the terms of the BSD 3-Clause License.
7|
8| The full license is in the file LICENSE, distributed with this software.
9|----------------------------------------------------------------------------*/
10import { IIterator, iter, IterableOrArrayLike } from './iter';
11
12/**
13 * Transform the values of an iterable with a mapping function.
14 *
15 * @param object - The iterable or array-like object of interest.
16 *
17 * @param fn - The mapping function to invoke for each value.
18 *
19 * @returns An iterator which yields the transformed values.
20 *
21 * #### Example
22 * ```typescript
23 * import { map, toArray } from '@lumino/algorithm';
24 *
25 * let data = [1, 2, 3];
26 *
27 * let stream = map(data, value => value * 2);
28 *
29 * toArray(stream); // [2, 4, 6]
30 * ```
31 */
32export function map<T, U>(
33 object: IterableOrArrayLike<T>,
34 fn: (value: T, index: number) => U
35): IIterator<U> {
36 return new MapIterator<T, U>(iter(object), fn);
37}
38
39/**
40 * An iterator which transforms values using a mapping function.
41 */
42export class MapIterator<T, U> implements IIterator<U> {
43 /**
44 * Construct a new map iterator.
45 *
46 * @param source - The iterator of values of interest.
47 *
48 * @param fn - The mapping function to invoke for each value.
49 */
50 constructor(source: IIterator<T>, fn: (value: T, index: number) => U) {
51 this._source = source;
52 this._fn = fn;
53 }
54
55 /**
56 * Get an iterator over the object's values.
57 *
58 * @returns An iterator which yields the object's values.
59 */
60 iter(): IIterator<U> {
61 return this;
62 }
63
64 /**
65 * Create an independent clone of the iterator.
66 *
67 * @returns A new independent clone of the iterator.
68 */
69 clone(): IIterator<U> {
70 let result = new MapIterator<T, U>(this._source.clone(), this._fn);
71 result._index = this._index;
72 return result;
73 }
74
75 /**
76 * Get the next value from the iterator.
77 *
78 * @returns The next value from the iterator, or `undefined`.
79 */
80 next(): U | undefined {
81 let value = this._source.next();
82 if (value === undefined) {
83 return undefined;
84 }
85 return this._fn.call(undefined, value, this._index++);
86 }
87
88 private _index = 0;
89 private _source: IIterator<T>;
90 private _fn: (value: T, index: number) => U;
91}