OLD | NEW |
| (Empty) |
1 // Copyright 2013 Google Inc. All Rights Reserved. | |
2 // | |
3 // Licensed under the Apache License, Version 2.0 (the "License"); | |
4 // you may not use this file except in compliance with the License. | |
5 // You may obtain a copy of the License at | |
6 // | |
7 // http://www.apache.org/licenses/LICENSE-2.0 | |
8 // | |
9 // Unless required by applicable law or agreed to in writing, software | |
10 // distributed under the License is distributed on an "AS IS" BASIS, | |
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
12 // See the License for the specific language governing permissions and | |
13 // limitations under the License. | |
14 | |
15 part of quiver.iterables; | |
16 | |
17 /** | |
18 * Returns an [Iterable] of [List]s where the nth element in the returned | |
19 * iterable contains the nth element from every Iterable in [iterables]. The | |
20 * returned Iterable is as long as the shortest Iterable in the argument. If | |
21 * [iterables] is empty, it returns an empty list. | |
22 */ | |
23 Iterable<List> zip(Iterable<Iterable> iterables) => | |
24 (iterables.isEmpty) ? const [] : new _Zip(iterables); | |
25 | |
26 class _Zip extends IterableBase<List> { | |
27 final Iterable<Iterable> iterables; | |
28 | |
29 _Zip(Iterable<Iterable> this.iterables); | |
30 | |
31 Iterator<List> get iterator => new _ZipIterator( | |
32 iterables.map((i) => i.iterator).toList(growable: false)); | |
33 } | |
34 | |
35 class _ZipIterator implements Iterator<List> { | |
36 final List<Iterator> _iterators; | |
37 List _current; | |
38 | |
39 _ZipIterator(List<Iterator> this._iterators); | |
40 | |
41 List get current => _current; | |
42 | |
43 bool moveNext() { | |
44 bool hasNext = true; | |
45 var newValue = new List(_iterators.length); | |
46 for (int i = 0; i < _iterators.length; i++) { | |
47 var iter = _iterators[i]; | |
48 hasNext = hasNext && iter.moveNext(); | |
49 newValue[i] = iter.current; | |
50 } | |
51 _current = (hasNext) ? newValue : null; | |
52 return hasNext; | |
53 } | |
54 } | |
OLD | NEW |