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 /// Returns an [Iterable] of [IndexedValue]s where the nth value holds the nth | |
18 /// element of [iterable] and its index. | |
19 Iterable<IndexedValue> enumerate(Iterable iterable) => | |
20 new EnumerateIterable(iterable); | |
21 | |
22 class IndexedValue<V> { | |
23 final int index; | |
24 final V value; | |
25 | |
26 IndexedValue(this.index, this.value); | |
27 | |
28 operator ==(o) => o is IndexedValue && o.index == index && o.value == value; | |
29 int get hashCode => index * 31 + value.hashCode; | |
30 String toString() => '($index, $value)'; | |
31 } | |
32 | |
33 /// An [Iterable] of [IndexedValue]s where the nth value holds the nth | |
34 /// element of [iterable] and its index. See [enumerate]. | |
35 // This was inspired by MappedIterable internal to Dart collections. | |
36 class EnumerateIterable<V> extends IterableBase<IndexedValue<V>> { | |
37 final Iterable<V> _iterable; | |
38 | |
39 EnumerateIterable(this._iterable); | |
40 | |
41 Iterator<IndexedValue<V>> get iterator => | |
42 new EnumerateIterator<V>(_iterable.iterator); | |
43 | |
44 // Length related functions are independent of the mapping. | |
45 int get length => _iterable.length; | |
46 bool get isEmpty => _iterable.isEmpty; | |
47 | |
48 // Index based lookup can be done before transforming. | |
49 IndexedValue<V> get first => new IndexedValue<V>(0, _iterable.first); | |
50 IndexedValue<V> get last => new IndexedValue<V>(length - 1, _iterable.last); | |
51 IndexedValue<V> get single => new IndexedValue<V>(0, _iterable.single); | |
52 IndexedValue<V> elementAt(int index) => | |
53 new IndexedValue<V>(index, _iterable.elementAt(index)); | |
54 } | |
55 | |
56 /// The [Iterator] returned by [EnumerateIterable.iterator]. | |
57 class EnumerateIterator<V> extends Iterator<IndexedValue<V>> { | |
58 final Iterator<V> _iterator; | |
59 int _index = 0; | |
60 IndexedValue<V> _current; | |
61 | |
62 EnumerateIterator(this._iterator); | |
63 | |
64 IndexedValue<V> get current => _current; | |
65 | |
66 bool moveNext() { | |
67 if (_iterator.moveNext()) { | |
68 _current = new IndexedValue(_index++, _iterator.current); | |
69 return true; | |
70 } | |
71 _current = null; | |
72 return false; | |
73 } | |
74 } | |
OLD | NEW |