Last active
December 16, 2015 13:39
-
-
Save buzzdecafe/5443104 to your computer and use it in GitHub Desktop.
infinite stream fibonacci generator
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
/* | |
Fibonacci infinite stream generator. Not hugely exciting yet | |
*/ | |
var fgen = (function() { | |
var fn1 = 0, fn2 = 1; | |
f = function f() { | |
var curr = fn2; | |
fn2 = fn1; | |
fn1 = fn1 + curr; | |
return fn1; | |
}; | |
f.reset = function() { | |
fn1 = 0; | |
fn2 = 1; | |
} | |
return f; | |
}()); | |
function Generator(fn) { | |
this.next = fn; | |
this.reset = fn.reset || function(){}; | |
} | |
var g = new Generator(fgen); | |
g.next(); // => 1 | |
g.next(); // => 1 | |
g.next(); // => 2 | |
g.next(); // => 3 | |
g.next(); // => 5 | |
g.next(); // => 8 | |
g.next(); // => 13 | |
g.reset(); | |
g.next(); // => 1 | |
g.next(); // => 1 | |
g.next(); // => 2 | |
// etc. => |
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
//not a generator; | |
function r(from, to) { | |
var f = from, t = to, a = []; | |
if (typeof t === "undefined") { | |
t = f; | |
f = 1; | |
} | |
if (t < f) { | |
throw new RangeError("c'mon man"); | |
} | |
while(f <= t) { | |
a.push(f++); | |
} | |
return a; | |
} | |
function range(from) { | |
return function(to) { | |
return from > to ? [] : cons(from, range(from+1)(to)); | |
} | |
} | |
function range(from, to) { | |
return from > to ? [] : [from].concat(range(from+1, to)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment