Skip to content

Instantly share code, notes, and snippets.

@jurosh
Last active September 27, 2016 18:57
Show Gist options
  • Save jurosh/e293fd022e83db0efd11832f5eb9a872 to your computer and use it in GitHub Desktop.
Save jurosh/e293fd022e83db0efd11832f5eb9a872 to your computer and use it in GitHub Desktop.
Fibonacci sequence - javascript generator
function * fibon () {
let val1 = 0;
let val2 = 1;
let swap;
yield val1;
yield val2;
while (true) {
swap = val1 + val2;
val1 = val2;
val2 = swap;
yield swap;
}
}
// Usage like:
let fib = fibon();
console.log(fib.next()); // 0
console.log(fib.next()); // 1
console.log(fib.next()); // 1
console.log(fib.next()); // 2
console.log(fib.next()); // 3
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment