UNPKG

2.43 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 * Iterate over an iterable using a stepped increment.
14 *
15 * @param object - The iterable or array-like object of interest.
16 *
17 * @param step - The distance to step on each iteration. A value
18 * of less than `1` will behave the same as a value of `1`.
19 *
20 * @returns An iterator which traverses the iterable step-wise.
21 *
22 * #### Example
23 * ```typescript
24 * import { stride, toArray } from '@lumino/algorithm';
25 *
26 * let data = [1, 2, 3, 4, 5, 6];
27 *
28 * let stream = stride(data, 2);
29 *
30 * toArray(stream); // [1, 3, 5];
31 * ```
32 */
33export function stride<T>(
34 object: IterableOrArrayLike<T>,
35 step: number
36): IIterator<T> {
37 return new StrideIterator<T>(iter(object), step);
38}
39
40/**
41 * An iterator which traverses a source iterator step-wise.
42 */
43export class StrideIterator<T> implements IIterator<T> {
44 /**
45 * Construct a new stride iterator.
46 *
47 * @param source - The iterator of values of interest.
48 *
49 * @param step - The distance to step on each iteration. A value
50 * of less than `1` will behave the same as a value of `1`.
51 */
52 constructor(source: IIterator<T>, step: number) {
53 this._source = source;
54 this._step = step;
55 }
56
57 /**
58 * Get an iterator over the object's values.
59 *
60 * @returns An iterator which yields the object's values.
61 */
62 iter(): IIterator<T> {
63 return this;
64 }
65
66 /**
67 * Create an independent clone of the iterator.
68 *
69 * @returns A new independent clone of the iterator.
70 */
71 clone(): IIterator<T> {
72 return new StrideIterator<T>(this._source.clone(), this._step);
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(): T | undefined {
81 let value = this._source.next();
82 for (let n = this._step - 1; n > 0; --n) {
83 this._source.next();
84 }
85 return value;
86 }
87
88 private _source: IIterator<T>;
89 private _step: number;
90}