OLD | NEW |
| (Empty) |
1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file | |
2 // for details. All rights reserved. Use of this source code is governed by a | |
3 // BSD-style license that can be found in the LICENSE file. | |
4 | |
5 /** | |
6 * Zipping multiple iterables into one iterable of tuples of values. | |
7 */ | |
8 library dart.pkg.collection.iterable_zip; | |
9 | |
10 import "dart:collection" show IterableBase; | |
11 | |
12 /** | |
13 * Iterable that iterates over lists of values from other iterables. | |
14 * | |
15 * When [iterator] is read, an [Iterator] is created for each [Iterable] in | |
16 * the [Iterable] passed to the constructor. | |
17 * | |
18 * As long as all these iterators have a next value, those next values are | |
19 * combined into a single list, which becomes the next value of this | |
20 * [Iterable]'s [Iterator]. As soon as any of the iterators run out, | |
21 * the zipped iterator also stops. | |
22 */ | |
23 class IterableZip extends IterableBase<List> { | |
24 final Iterable<Iterable> _iterables; | |
25 IterableZip(Iterable<Iterable> iterables) | |
26 : this._iterables = iterables; | |
27 | |
28 /** | |
29 * Returns an iterator that combines values of the iterables' iterators | |
30 * as long as they all have values. | |
31 */ | |
32 Iterator<List> get iterator { | |
33 List iterators = _iterables.map((x) => x.iterator).toList(growable: false); | |
34 // TODO(lrn): Return an empty iterator directly if iterators is empty? | |
35 return new _IteratorZip(iterators); | |
36 } | |
37 } | |
38 | |
39 class _IteratorZip implements Iterator<List> { | |
40 final List<Iterator> _iterators; | |
41 List _current; | |
42 _IteratorZip(List iterators) : _iterators = iterators; | |
43 bool moveNext() { | |
44 if (_iterators.isEmpty) return false; | |
45 for (int i = 0; i < _iterators.length; i++) { | |
46 if (!_iterators[i].moveNext()) { | |
47 _current = null; | |
48 return false; | |
49 } | |
50 } | |
51 _current = new List(_iterators.length); | |
52 for (int i = 0; i < _iterators.length; i++) { | |
53 _current[i] = _iterators[i].current; | |
54 } | |
55 return true; | |
56 } | |
57 | |
58 List get current => _current; | |
59 } | |
OLD | NEW |