Created
August 17, 2012 04:33
-
-
Save pranavraja/3375950 to your computer and use it in GitHub Desktop.
Node.js generators, inspired by Python
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
// 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
commented
Aug 17, 2012
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment