Skip to content

Instantly share code, notes, and snippets.

@hg-pyun
Last active October 4, 2018 14:53
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 hg-pyun/545179b28cfd116c9a38356458022470 to your computer and use it in GitHub Desktop.
Save hg-pyun/545179b28cfd116c9a38356458022470 to your computer and use it in GitHub Desktop.
iterator.02.js
function makeRangeIterator(start = 0, end = Infinity, step = 1) {
var nextIndex = start;
var n = 0;
var rangeIterator = {
next: function() {
var result;
if (nextIndex < end) {
result = { value: nextIndex, done: false }
} else if (nextIndex == end) {
result = { value: n, done: true }
} else {
result = { done: true };
nextIndex += step;
n++;
return result;
}
};
return rangeIterator;
}
// run iterator
const it = makeRangeIterator(1, 4);
let result = it.next();
while (!result.done) {
console.log(result.value); // 1 2 3
result = it.next();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment