Last active
October 4, 2018 14:53
-
-
Save hg-pyun/545179b28cfd116c9a38356458022470 to your computer and use it in GitHub Desktop.
iterator.02.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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