Skip to content

Instantly share code, notes, and snippets.

@bidiu
Created March 12, 2019 17:45
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 bidiu/8a50a30dca3e21f3e4d477d82cf6a4ca to your computer and use it in GitHub Desktop.
Save bidiu/8a50a30dca3e21f3e4d477d82cf6a4ca to your computer and use it in GitHub Desktop.
implementing range using iterator and generator
class RangeIterable {
constructor(start, end, step) {
this.start = start;
this.end = end;
this.step = step;
this.cnt = start;
}
[Symbol.iterator]() {
return this;
}
next() {
const done = this.cnt >= this.end;
if (done) {
return { done, value: undefined };
}
const value = this.cnt;
this.cnt += this.step;
return { done, value };
}
}
function range(start, end, step = 1) {
return new RangeIterable(start, end, step);
}
function* range(start, end, step = 1) {
for (let i = start; i < end; i += step) {
yield i;
}
}
for (let v of range(1, 10, 3)) {
console.log(v);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment