Skip to content

Instantly share code, notes, and snippets.

@masnun
Created July 5, 2019 07:13
Show Gist options
  • Save masnun/c6b699ec39893c92e1d24e5bf8819410 to your computer and use it in GitHub Desktop.
Save masnun/c6b699ec39893c92e1d24e5bf8819410 to your computer and use it in GitHub Desktop.
class RangeIterator implements Iterator<number> {
constructor(private n: number, private to: number) {}
next(): IteratorResult<number> {
if (this.n <= this.to) {
return { done: false, value: this.n++ };
} else {
return { done: true, value: undefined };
}
}
}
class AsyncRangeIterator implements AsyncIterator<number> {
constructor(private n: number, private to: number) {}
async next(): Promise<IteratorResult<number>> {
await new Promise(resolve => setTimeout(resolve, 3000));
if (this.n <= this.to) {
return { done: false, value: this.n++ };
} else {
return { done: true, value: undefined };
}
}
}
class MyRange {
constructor(private start: number, private end: number) {}
[Symbol.iterator]() {
return new RangeIterator(this.start, this.end);
}
[Symbol.asyncIterator]() {
return new AsyncRangeIterator(this.start, this.end);
}
}
const range = new MyRange(0, 10);
for (let n of range) {
console.log(n);
}
(async () => {
for await (let n of range) {
console.log(n);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment