UNPKG

2.34 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 * Enumerate an iterable object.
14 *
15 * @param object - The iterable or array-like object of interest.
16 *
17 * @param start - The starting enum value. The default is `0`.
18 *
19 * @returns An iterator which yields the enumerated values.
20 *
21 * #### Example
22 * ```typescript
23 * import { enumerate, toArray } from '@lumino/algorithm';
24 *
25 * let data = ['foo', 'bar', 'baz'];
26 *
27 * let stream = enumerate(data, 1);
28 *
29 * toArray(stream); // [[1, 'foo'], [2, 'bar'], [3, 'baz']]
30 * ```
31 */
32export function enumerate<T>(
33 object: IterableOrArrayLike<T>,
34 start = 0
35): IIterator<[number, T]> {
36 return new EnumerateIterator<T>(iter(object), start);
37}
38
39/**
40 * An iterator which enumerates the source values.
41 */
42export class EnumerateIterator<T> implements IIterator<[number, T]> {
43 /**
44 * Construct a new enumerate iterator.
45 *
46 * @param source - The iterator of values of interest.
47 *
48 * @param start - The starting enum value.
49 */
50 constructor(source: IIterator<T>, start: number) {
51 this._source = source;
52 this._index = start;
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<[number, T]> {
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<[number, T]> {
70 return new EnumerateIterator<T>(this._source.clone(), this._index);
71 }
72
73 /**
74 * Get the next value from the iterator.
75 *
76 * @returns The next value from the iterator, or `undefined`.
77 */
78 next(): [number, T] | undefined {
79 let value = this._source.next();
80 if (value === undefined) {
81 return undefined;
82 }
83 return [this._index++, value];
84 }
85
86 private _source: IIterator<T>;
87 private _index: number;
88}