iteragain
Version:
Javascript Iterable/Iterator/Generator-function utilities.
73 lines • 2.47 kB
JavaScript
/**
* Wraps `iterator` to allow for seeking backwards and forwards. An internal cache of length `maxLength` is kept and
* progressively added to when iterating forwards.
*/
export class SeekableIterator {
constructor(iterator, maxLength = Infinity) {
this.iterator = iterator;
this.maxLength = maxLength;
this.cache = [];
/** Absolute index of the next value `next()` will return. */
this.i = 0;
/** Absolute index of `cache[0]`. Increments when the cache evicts its oldest entry. */
this.base = 0;
this.iteratorDone = false;
}
get elements() {
return this.cache;
}
get done() {
return this.iteratorDone ? !this.cache.length || this.i >= this.base + this.cache.length : false;
}
[Symbol.iterator]() {
return this;
}
next(...args) {
if (this.done)
return { done: true, value: undefined };
if (this.i < this.base + this.cache.length) {
return { done: false, value: this.cache[this.i++ - this.base] };
}
const next = this.iterator.next(...args);
if (next.done) {
this.iteratorDone = true;
return next;
}
this.add(next.value);
return { done: false, value: this.cache[this.i++ - this.base] };
}
/**
* Seeks forward/backwards to the index `i`. `i` may be any positive or negative number. Negative numbers seek
* starting from the end of the internal cache (e.g. -1 is the last element).
*/
seek(i) {
if (i < 0)
i = this.base + this.cache.length + i;
if (i > this.i)
while (this.i < i && !this.done)
this.next();
else if (i < this.i)
this.i = Math.max(i, this.base);
}
/**
* Peek ahead of where the current iteration is. This doesn't consume any values of the iterator.
* @param ahead optional, the number of elements to peek ahead.
*/
peek(ahead = 1) {
const result = [];
for (let i = 0; i < ahead; i++)
result.push(this.next().value);
this.i -= ahead;
return result;
}
/** Add `value` to the `cache`. */
add(value) {
this.cache.push(value);
if (this.cache.length > this.maxLength) {
this.cache.shift();
this.base++;
}
}
}
export default SeekableIterator;
//# sourceMappingURL=SeekableIterator.js.map