OLD | NEW |
| (Empty) |
1 // Copyright 2014 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 Iterable generate(initial(), next(o)) => new GeneratingIterable(initial, next); | |
18 | |
19 /** | |
20 * An Iterable who's first value is [object] and who's subsequent values are | |
21 * generated by passing the current value to the [next] function. | |
22 * | |
23 * The class is useful for creating lazy iterables from object hierarchies and | |
24 * graphs. | |
25 * | |
26 * It's important that for the given initial value and next function that the | |
27 * sequence of items eventually terminates. Otherwise calling methods that | |
28 * expect a finite sequence, like `length` or `last`, will cause an infinite | |
29 * loop. | |
30 * | |
31 * Example: | |
32 * | |
33 * class Node { | |
34 * Node parent; | |
35 * | |
36 * /** | |
37 * * An iterable of node and all ancestors up to the root. | |
38 * */ | |
39 * Iterable<Node> ancestors = | |
40 * new GeneratingIterable<Node>(() => this, (n) => n.parent); | |
41 * | |
42 * /** | |
43 * * An iterable of the root and the path of nodes to this. The reverse | |
44 * * of ancestors. | |
45 * */ | |
46 * Iterable<Node> path = ancestors.toList().reversed(); | |
47 * } | |
48 * | |
49 */ | |
50 class GeneratingIterable<T> extends IterableBase<T> { | |
51 final initial; | |
52 final next; | |
53 | |
54 GeneratingIterable(T this.initial(), T this.next(T o)); | |
55 | |
56 @override | |
57 Iterator<T> get iterator => new _GeneratingIterator(initial(), next); | |
58 } | |
59 | |
60 class _GeneratingIterator<T> implements Iterator<T> { | |
61 final next; | |
62 T object; | |
63 bool started = false; | |
64 | |
65 _GeneratingIterator(T this.object, T this.next(T o)); | |
66 | |
67 @override | |
68 T get current => started ? object : null; | |
69 | |
70 @override | |
71 bool moveNext() { | |
72 if (object == null) return false; | |
73 if (started) { | |
74 object = next(object); | |
75 } else { | |
76 started = true; | |
77 } | |
78 return object != null; | |
79 } | |
80 } | |
OLD | NEW |