Skip to content

Instantly share code, notes, and snippets.

@alexeykomov
Last active August 29, 2016 09:40
Show Gist options
  • Save alexeykomov/ead75f0293f17981e7ac to your computer and use it in GitHub Desktop.
Save alexeykomov/ead75f0293f17981e7ac to your computer and use it in GitHub Desktop.
Fibonacci numbers via generator in JavaScript.
function* fibonacci() {
var earlierPrev = 0;
var prev = 0;
var index = -1;
while (true) {
index++;
if (index == 0) {
yield 0;
} else if (index == 1) {
prev = 1;
yield 1;
} else {
let res = earlierPrev + prev;
earlierPrev = prev;
prev = res;
yield res;
}
}
}
var f = fibonacci()
f.next()
f.next()
f.next()
f.next()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment