Skip to content

Instantly share code, notes, and snippets.

@bergwerf
Created January 20, 2019 00:28
Show Gist options
  • Select an option

  • Save bergwerf/b62bd7b4a282389778443163a1af2820 to your computer and use it in GitHub Desktop.

Select an option

Save bergwerf/b62bd7b4a282389778443163a1af2820 to your computer and use it in GitHub Desktop.
Cached iterator
/// 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