Skip to content

Instantly share code, notes, and snippets.

@hk-skit
Created January 27, 2019 05:08
Show Gist options
  • Save hk-skit/582a779c9696e1acd956404c78c084ba to your computer and use it in GitHub Desktop.
Save hk-skit/582a779c9696e1acd956404c78c084ba to your computer and use it in GitHub Desktop.
class RangeIterator {
constructor({
start = 0,
end = 1000,
step = 1
}) {
this.start = start;
this.end = end;
this.step = step;
}
[Symbol.iterator]() {
let start = this.start;
const iterable = {
// Next fn complying with Iterator protocol.
next: () => {
if (start <= this.end) {
const result = {
value: start,
done: false
};
start += this.step;
return result;
}
return {
done: true
};
}
}
return iterable;;
}
}
const range = new RangeIterator({
start: 0,
end: 20,
step: 5
});
console.log(...range); // 0 5 10 15 20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment