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 | |----------------------------------------------------------------------------*/
|
10 | import { IIterator, iter, IterableOrArrayLike } from './iter';
|
11 |
|
12 | /**
|
13 | * Iterate several iterables in lockstep.
|
14 | *
|
15 | * @param objects - The iterable or array-like objects of interest.
|
16 | *
|
17 | * @returns An iterator which yields successive tuples of values where
|
18 | * each value is taken in turn from the provided iterables. It will
|
19 | * be as long as the shortest provided iterable.
|
20 | *
|
21 | * #### Example
|
22 | * ```typescript
|
23 | * import { zip, toArray } from '@lumino/algorithm';
|
24 | *
|
25 | * let data1 = [1, 2, 3];
|
26 | * let data2 = [4, 5, 6];
|
27 | *
|
28 | * let stream = zip(data1, data2);
|
29 | *
|
30 | * toArray(stream); // [[1, 4], [2, 5], [3, 6]]
|
31 | * ```
|
32 | */
|
33 | export function zip<T>(...objects: IterableOrArrayLike<T>[]): IIterator<T[]> {
|
34 | return new ZipIterator<T>(objects.map(iter));
|
35 | }
|
36 |
|
37 | /**
|
38 | * An iterator which iterates several sources in lockstep.
|
39 | */
|
40 | export class ZipIterator<T> implements IIterator<T[]> {
|
41 | /**
|
42 | * Construct a new zip iterator.
|
43 | *
|
44 | * @param source - The iterators of interest.
|
45 | */
|
46 | constructor(source: IIterator<T>[]) {
|
47 | this._source = source;
|
48 | }
|
49 |
|
50 | /**
|
51 | * Get an iterator over the object's values.
|
52 | *
|
53 | * @returns An iterator which yields the object's values.
|
54 | */
|
55 | iter(): IIterator<T[]> {
|
56 | return this;
|
57 | }
|
58 |
|
59 | /**
|
60 | * Create an independent clone of the iterator.
|
61 | *
|
62 | * @returns A new independent clone of the iterator.
|
63 | */
|
64 | clone(): IIterator<T[]> {
|
65 | return new ZipIterator<T>(this._source.map(it => it.clone()));
|
66 | }
|
67 |
|
68 | /**
|
69 | * Get the next value from the iterator.
|
70 | *
|
71 | * @returns The next value from the iterator, or `undefined`.
|
72 | */
|
73 | next(): T[] | undefined {
|
74 | let result = new Array<T>(this._source.length);
|
75 | for (let i = 0, n = this._source.length; i < n; ++i) {
|
76 | let value = this._source[i].next();
|
77 | if (value === undefined) {
|
78 | return undefined;
|
79 | }
|
80 | result[i] = value;
|
81 | }
|
82 | return result;
|
83 | }
|
84 |
|
85 | private _source: IIterator<T>[];
|
86 | }
|