Skip to content

Instantly share code, notes, and snippets.

@Clokze
Created November 27, 2013 19:42
Show Gist options
  • Select an option

  • Save Clokze/7681927 to your computer and use it in GitHub Desktop.

Select an option

Save Clokze/7681927 to your computer and use it in GitHub Desktop.
Fibers fibonacci
var Fiber = 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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment