Created
January 20, 2019 00:28
-
-
Save bergwerf/b62bd7b4a282389778443163a1af2820 to your computer and use it in GitHub Desktop.
Cached iterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// Proxy iterator for [origin] that caches the result so that it can be | |
| /// iterated again using [rewind]. Multiple rewinded copies of this iterator | |
| /// share the [sharedCache] so it doesn't matter which one reads from [origin]. | |
| class CachedIterator<T> implements Iterator<T> { | |
| var _i = -1; | |
| var _terminated = false; | |
| final Iterator<T> origin; | |
| final List<T> sharedCache; | |
| CachedIterator(this.origin, [List<T> cache]) | |
| : sharedCache = cache ?? new List<T>(); | |
| @override | |
| T get current => _i != -1 && _i < sharedCache.length ? sharedCache[_i] : null; | |
| @override | |
| bool moveNext() { | |
| if (_terminated) { | |
| return false; | |
| } | |
| _i++; | |
| if (_i < sharedCache.length) { | |
| return true; | |
| } else { | |
| assert(_i == sharedCache.length); | |
| if (origin.moveNext()) { | |
| sharedCache.add(origin.current); | |
| return true; | |
| } else { | |
| _terminated = true; | |
| return false; | |
| } | |
| } | |
| } | |
| /// Get rewinded copy of this iterator. | |
| CachedIterator<T> rewind() => new CachedIterator(origin, sharedCache); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment