Created
June 9, 2017 20:42
-
-
Save halferty/f3f93baaea9d379b3c77b4044064c4ac to your computer and use it in GitHub Desktop.
JS Generators example
This file contains hidden or 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* exampleGenerator(i) { | |
yield i + 1; | |
yield i + 2; | |
yield i + 3; | |
} | |
function run(iter) { | |
let done = false; | |
while (!done) { | |
({ value, done } = iter.next()); | |
if (!done) { | |
console.log(value); | |
} | |
} | |
} | |
run(exampleGenerator(2)); | |
/*----------------------*/ | |
function* exampleGenerator2(m) { | |
while (true) { | |
const n = yield; | |
console.log(n + m); | |
} | |
} | |
function run2(iter) { | |
iter.next(); // Run the generator until the first `yield` statement | |
iter.next(1); | |
iter.next(2); | |
iter.next(3); | |
iter.return(); | |
} | |
run2(exampleGenerator2(2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment