Skip to content

Instantly share code, notes, and snippets.

@yosriady
Last active August 29, 2015 13:59
Show Gist options
  • Select an option

  • Save yosriady/10453401 to your computer and use it in GitHub Desktop.

Select an option

Save yosriady/10453401 to your computer and use it in GitHub Desktop.
Javascript Generators test
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