Created
May 23, 2011 11:47
-
-
Save msgodf/986586 to your computer and use it in GitHub Desktop.
Generator/lazy sequence class for JavaScript
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
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);}};} |
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
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