Last active
May 30, 2016 10:21
-
-
Save qmmr/f0cdf5452f5703dbef1836338e048cc5 to your computer and use it in GitHub Desktop.
Fibonacci sequence using 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
function fibonacci(max) { | |
var prev = 0 | |
var curr = 1 | |
var temp = 0 | |
var i = 0 | |
var out = [] | |
for (; prev < max; i++) { | |
out.push(prev) | |
temp = prev | |
prev = curr | |
curr = temp + curr | |
} | |
return out | |
} | |
var sequence = fibonacci(100) | |
console.log('Marcin: fibonacci sequence: ', sequence); | |
module.exports = fibonacci |
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
function* fibonacci(max = 1000) { | |
let [ prev, curr ] = [ 0, 1 ] | |
while (prev < max) { | |
yield prev; // the only place where you HAVE to put semicolon... | |
;[ prev, curr ] = [ curr, prev + curr ] // unless you want to do it at the beginning, your choice... | |
} | |
} | |
// get fibonacci numbers up to 100 | |
const sequence = [] | |
for (let num of fibonacci(100)) { | |
sequence.push(num) | |
} | |
console.log('Marcin: fibonacci sequence: ', sequence) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment