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 * Contains functions that are included by default in [PolymerExpressions]. |
| 7 * |
| 8 * - [enumerate]: a convenient way to iterate over items and the indexes. |
| 9 */ |
| 10 // Code from https://github.com/google/quiver-dart/commit/52edc4baf37e99ff6a8f99
c648b29b135fc0b880 |
| 11 library polymer_expressions.src.globals; |
| 12 |
| 13 import 'dart:collection'; |
| 14 |
| 15 /** |
| 16 * Returns an [Iterable] of [IndexedValue]s where the nth value holds the nth |
| 17 * element of [iterable] and its index. |
| 18 */ |
| 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 |
| 29 |
| 30 /** |
| 31 * An [Iterable] of [IndexedValue]s where the nth value holds the nth |
| 32 * element of [iterable] and its index. See [enumerate]. |
| 33 */ |
| 34 // This was inspired by MappedIterable internal to Dart collections. |
| 35 class EnumerateIterable<V> extends IterableBase<IndexedValue<V>> { |
| 36 final Iterable<V> _iterable; |
| 37 |
| 38 EnumerateIterable(this._iterable); |
| 39 |
| 40 Iterator<V> get iterator => new EnumerateIterator<V>(_iterable.iterator); |
| 41 |
| 42 // Length related functions are independent of the mapping. |
| 43 int get length => _iterable.length; |
| 44 bool get isEmpty => _iterable.isEmpty; |
| 45 |
| 46 // Index based lookup can be done before transforming. |
| 47 IndexedValue<V> get first => new IndexedValue<V>(0, _iterable.first); |
| 48 IndexedValue<V> get last => new IndexedValue<V>(length - 1, _iterable.last); |
| 49 IndexedValue<V> get single => new IndexedValue<V>(0, _iterable.single); |
| 50 IndexedValue<V> elementAt(int index) => |
| 51 new IndexedValue<V>(index, _iterable.elementAt(index)); |
| 52 } |
| 53 |
| 54 /** The [Iterator] returned by [EnumerateIterable.iterator]. */ |
| 55 class EnumerateIterator<V> extends Iterator<IndexedValue<V>> { |
| 56 final Iterator<IndexedValue<V>> _iterator; |
| 57 int _index = 0; |
| 58 IndexedValue<V> _current; |
| 59 |
| 60 EnumerateIterator(this._iterator); |
| 61 |
| 62 IndexedValue<V> get current => _current; |
| 63 |
| 64 bool moveNext() { |
| 65 if (_iterator.moveNext()) { |
| 66 _current = new IndexedValue(_index++, _iterator.current); |
| 67 return true; |
| 68 } |
| 69 _current = null; |
| 70 return false; |
| 71 } |
| 72 } |
OLD | NEW |