Last active
August 29, 2016 09:40
-
-
Save alexeykomov/ead75f0293f17981e7ac to your computer and use it in GitHub Desktop.
Fibonacci numbers via generator in JavaScript.
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
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