Skip to content

Instantly share code, notes, and snippets.

@msgodf
Created May 22, 2011 17:01
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/985674 to your computer and use it in GitHub Desktop.
Save msgodf/985674 to your computer and use it in GitHub Desktop.
Fibonacci sequence generator
class fib_generator
constructor: ->
last = 0
current = 1
@first = ->
last = 0
current = 1
@next = ->
temp = last
last = current
current = current + temp
fib = new fib_generator
fib = (function() {
var current = 1,
next = 1;
return {
first: function() {
current = next = 1;
return current;
},
next: function() {
var temp = current;
current = next;
next = current + temp;
return current;
}
}
})()
fib=(function(a,b){a=b=1;return{first:function(){return a=b=1;},next:function(){return a=[b,b+=a][0];}}})()
fib = (function () {
var s = [ 1 , 1 ],
i = 0;
return {
first: function() {
i = 0;
return s[ i ];
},
next: function() {
i = i + 1;
if ( typeof( s[ i ] ) === "undefined" ) {
s[ i ] = s[ i - 2 ] + s[ i - 1 ];
}
return s[ i ];
},
nth: function( n ) {
while ( typeof( s[ n ] ) === "undefined" ) {
this.next();
}
return s[ n ];
},
take: function( n ) {
// Ensure that the nth element has been generated
this.nth( n );
return s.slice( 0 , n );
}
};
})()
fib=(function(s,i){s=[1,1];i=0;return{first:function(){return s[i=0];},next:function(){return s.length<=++i?s[i]=s[i-2]+s[i-1]: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);}};})()
fib=(function(s,i){s=[1,1];i=0;return{first:function(){return s[i=0];},next:function(){return s.length<=++i?s[i]=s[i-2]+s[i-1]:s[i];}}})()
@msgodf
Copy link
Author

msgodf commented May 22, 2011

A series of generator functions for the Fibonacci sequence. A basic one, one including memoization, and a final one incorporating a large set of generator functionality (first,next,nth, and take).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment