Last active
July 2, 2018 02:42
-
-
Save randie/9fb6da821843a1fd1121f33279e74ecb to your computer and use it in GitHub Desktop.
simple generators example
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
// Demo: https://repl.it/@RandieBemis/ExampleES6Generators | |
// This is our generator function | |
// Each time it yields, it returns control to the caller of | |
// its iterators next() method | |
// A generator is a function that returns an iterator. | |
// An iterator is an object with a next() method. | |
function* g() { | |
yield 1; | |
yield 2; | |
yield 3; | |
yield 4; | |
} | |
console.log("\n// Part 1"); | |
const gIterator = g(); // returns g's iterator | |
console.log(gIterator.next().value); // 1 | |
console.log(gIterator.next().value); // 2 | |
console.log(gIterator.next().value); // 3 | |
console.log(gIterator.next().value); // 4 | |
console.log(gIterator.next().done); // true => We're done! | |
// for..of is a more convenient way to step thru all of g()'s values. | |
// g() returns its iterator. for..of automatically calls next() on | |
// that iterator, saves the value returned, until done. Basically it | |
// does everything we did manually above. | |
console.log("\n// Part 2"); | |
for (const value of g()) { | |
console.log(`value = ${value}`); | |
} | |
// calling g() resets its iterator back to the first value | |
console.log("\n// Part 3"); | |
console.log(g().next().value); // 1 | |
console.log(g().next().value); // 1 | |
console.log("\n// Part 4"); | |
for (const [index, value] of [1,2,3,4].entries()) { | |
console.log(index, value); | |
} | |
/* | |
// Output using Babel Compiler v6.4.4 | |
// Part 1 | |
1 | |
2 | |
3 | |
4 | |
true | |
// Part 2 | |
value = 1 | |
value = 2 | |
value = 3 | |
value = 4 | |
// Part 3 | |
1 | |
1 | |
// Part 4 | |
0 1 | |
1 2 | |
2 3 | |
3 4 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment