Last active
November 10, 2015 05:41
-
-
Save sonyseng/716593c5e4509d97f79a to your computer and use it in GitHub Desktop.
Using Generators to lazily build a collection of items in ES6 (babeljs)
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
// Infinitely generate all odd numbers or whatever the MAX Number is | |
function* oddNumbers() { | |
let i = 1 | |
// Infinite loop. But thanks to the yield keyword, we exit this | |
// loop and return a value. On the next call back in, we resume | |
// where we left off. | |
while(1) { | |
yield i; | |
// Imagine if this were an expensive computation | |
i += 2; | |
} | |
} | |
// Materialize n items from the iterable collection and place them | |
// in a new array | |
function take(n, iterable) { | |
let count = 0; | |
let taken = []; | |
for (let value of iterable) { | |
if (count >= n) { | |
break; | |
} | |
taken[count] = value; | |
count++; | |
} | |
return taken; | |
} | |
// Materialize 10 odd numbers in an array | |
console.log(take(10, oddNumbers())); | |
// Output should be: | |
// [1,3,5,7,9,11,13,15,17,19] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment