Created
August 4, 2011 05:47
-
-
Save laverdet/1124572 to your computer and use it in GitHub Desktop.
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
require('fibers'); | |
// Generator function. Returns a function which returns incrementing | |
// Fibonacci numbers with each call. | |
function Fibonacci() { | |
// Create a new fiber which yields sequential Fibonacci numbers | |
var fiber = Fiber(function() { | |
Fiber.yield(0); // F(0) -> 0 | |
var prev = 0, curr = 1; | |
while (true) { | |
Fiber.yield(curr); | |
var tmp = prev + curr; | |
prev = curr; | |
curr = tmp; | |
} | |
}); | |
// Return a bound handle to `run` on this fiber | |
return fiber.run.bind(fiber); | |
} | |
// Initialize a new Fibonacci sequence and iterate up to 1597 | |
var seq = Fibonacci(); | |
for (var ii = seq(); ii <= 1597; ii = seq()) { | |
console.log(ii); | |
} |
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
0 | |
1 | |
1 | |
2 | |
3 | |
5 | |
8 | |
13 | |
21 | |
34 | |
55 | |
89 | |
144 | |
233 | |
377 | |
610 | |
987 | |
1597 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment