Last active
August 29, 2015 13:59
-
-
Save yosriady/10453401 to your computer and use it in GitHub Desktop.
Javascript Generators test
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 generator(pfunc){ | |
| return function(){ // Generator object closure | |
| var i = 0; //state keeps track number of calls | |
| return { | |
| next: function(){ // iterator next() method | |
| var val = pfunc(i); //pfunc is the parameter function | |
| i++; | |
| return val; | |
| } | |
| }; | |
| }(); // we are scoping all variables and functions inside of this IIFE | |
| } | |
| function lazyPows(n) { | |
| return generator(function(i) { | |
| return Math.pow(i, n); | |
| }); | |
| } | |
| function lazyOdds() { | |
| return generator(function(i) { | |
| return 2*i + 1; | |
| }); | |
| } | |
| var squares = lazyPows(2); | |
| console.log(squares.next()); // 0, 1, 4, 9, ... | |
| var odds = lazyOdds(); | |
| console.log(odds.next()); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment