Last active
January 24, 2018 04:39
-
-
Save thebopshoobop/9e9978ef8d6ada10b68ad9ba11627cb0 to your computer and use it in GitHub Desktop.
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* genRange(start, stop) { | |
let curr = 0; | |
while (curr < stop) yield curr++; | |
} | |
const gen = genRange(0, 3); | |
console.log("generator:"); | |
for (let i of gen) { | |
console.log(i); // => 0, then 1, then 2 | |
} | |
for (let i of gen) { | |
console.log(i); // => ...nothing | |
} | |
const iterRange = (start, stop) => { | |
let current = start; | |
const next = () => { | |
if (current < stop) { | |
return { value: current++ }; | |
} else { | |
current = start; | |
return { done: true }; | |
} | |
}; | |
return { [Symbol.iterator]: () => ({ next }) }; | |
}; | |
const iter = iterRange(0, 3); | |
console.log("iterator"); | |
for (let i of iter) { | |
console.log(i); // => 0, then 1, then 2 | |
} | |
for (let i of iter) { | |
console.log(i); // => 0, then 1, then 2 | |
} | |
const hybridRange = (start, stop) => { | |
const next = function*() { | |
let current = start; | |
while (current < stop) { | |
yield current++; | |
} | |
}; | |
return { [Symbol.iterator]: next }; | |
}; | |
const hybrid = hybridRange(0, 3); | |
console.log("hybrid"); | |
for (let i of hybrid) { | |
console.log(i); // => 0, then 1, then 2 | |
} | |
for (let i of hybrid) { | |
console.log(i); // => 0, then 1, then 2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment