Skip to content

Instantly share code, notes, and snippets.

@taxilian
Last active December 17, 2019 19:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taxilian/af4d7b92a9c3ff7f61f311c080dab491 to your computer and use it in GitHub Desktop.
Save taxilian/af4d7b92a9c3ff7f61f311c080dab491 to your computer and use it in GitHub Desktop.
Untested prototype for a readahead iterator in typescript
class ReadAheadIterator<T extends any> implements AsyncIterator<T> {
currentQ: Promise<T>[] = [];
constructor(private readNext: Iterator<Promise<T>>, private readAheadCount: number = 5) {
this.readAhead();
}
[Symbol.asyncIterator]() { return this; }
readAhead() {
while (this.currentQ.length < this.readAheadCount) {
let res = this.readNext.next();
if (!res.done) {
this.currentQ.push(res.value);
} else {
break;
}
}
}
next(): Promise<IteratorResult<T>> {
if (!this.currentQ.length) {
return new Promise(res => res({
done: true,
value: void 0
}));
}
let res = this.currentQ.shift();
this.readAhead();
return res.then(v => ({
done: false,
value: v
}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment