Skip to content

Instantly share code, notes, and snippets.

@qmmr
Last active May 30, 2016 10:21
Show Gist options
  • Save qmmr/f0cdf5452f5703dbef1836338e048cc5 to your computer and use it in GitHub Desktop.
Save qmmr/f0cdf5452f5703dbef1836338e048cc5 to your computer and use it in GitHub Desktop.
Fibonacci sequence using generator
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
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