Skip to content

Instantly share code, notes, and snippets.

@pranavraja
Created August 17, 2012 04:33
Show Gist options
  • Save pranavraja/3375950 to your computer and use it in GitHub Desktop.
Save pranavraja/3375950 to your computer and use it in GitHub Desktop.
Node.js generators, inspired by Python
// Generators in node.js
var Generator = function (fn) {
this.results = [];
this.continuations = [];
this.yield = function (val) {
this.results.push(val);
};
this.continue = function (fn) {
this.continuations.push(fn);
};
this.next = function () {
this.continuations.forEach(function (continuation) {
continuation.call(this);
}, this);
if (this.results.length) {
return this.results.pop(0);
}
};
fn.call(this);
};
var count = new Generator(function () {
var i = 0;
this.continue(function () {
i++;
this.yield(i);
});
});
console.log('Counting from 1 to 10');
for (var i=0; i < 10; i++) {
console.log(count.next());
}
var fib = new Generator(function () {
var a = 1, b = 1;
this.continue(function () {
this.yield(a);
var next = a + b;
a = b;
b = next;
});
});
console.log('Fibonacci');
for (var i=0; i < 10; i++) {
console.log(fib.next());
}
@theleoborges
Copy link

;; cool fibonacci bro
(map second (take 20 (iterate (fn [[p n]]
                                [n (+ p n)])
                              [0 1])))

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