Skip to content

Instantly share code, notes, and snippets.

@msgodf
Created May 23, 2011 11:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msgodf/986586 to your computer and use it in GitHub Desktop.
Save msgodf/986586 to your computer and use it in GitHub Desktop.
Generator/lazy sequence class for JavaScript
function Generator(f,s,i){i=0;return{first:function(){return s[i=0];},next:function(){return s.length<=++i?s[i]=f(s):s[i];},nth:function(n){while(s.length<=n)this.next();return s[n];},take:function(n){this.nth(n);return s.slice(0,n);}};}
function Generator ( fn , state) {
var i = 0;
return {
first: function() {
i = 0;
return state[ i ];
},
next: function() {
i = i + 1;
if ( typeof( state[ i ] ) === "undefined" ) {
state[ i ] = fn( state );
}
return state[ i ];
},
nth: function( n ) {
while ( typeof( state[ n ] ) === "undefined" ) {
this.next();
}
return state[ n ];
},
take: function( n ) {
// Ensure that the nth element has been generated
this.nth( n );
return state.slice( 0 , n );
}
};
};
var integers = new Generator(function ( state ) {
return state[ state.length - 1 ] + 1;
}), [ 1 ]);
var fib = new Generator(function ( state ) {
return state[ state.length - 2 ] + state[ state.length - 1 ];
}), [ 1 , 1 ]);
var factorials = new Generator(function ( state ) {
return state[ state.length - 1 ] * ( state.length + 1 ) ];
}), [ 1 ]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment