Skip to content

Instantly share code, notes, and snippets.

@buzzdecafe
Last active December 16, 2015 13:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buzzdecafe/5443104 to your computer and use it in GitHub Desktop.
Save buzzdecafe/5443104 to your computer and use it in GitHub Desktop.
infinite stream fibonacci generator
/*
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. =>
//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