Last active
June 23, 2020 01:06
-
-
Save deadkff01/eb5d0926182e1c2caa45e29abe7ba64a to your computer and use it in GitHub Desktop.
Fibonacci implementations in js
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
// implementation with Array | |
const fibo = len => | |
new Array(len).fill(1).reduce((acc, _, index) => { | |
const value = | |
index === 0 || index === 1 | |
? index | |
: acc[acc.length - 2] + acc[acc.length - 1]; | |
acc.push(value); | |
return acc; | |
}, []); | |
const fiboArray = fibo(10); | |
console.log(fiboArray); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] | |
// implementation with generators | |
function* fiboGen(len, current = 0, next = 1) { | |
if (len === 0) { | |
return current; | |
} | |
yield current; | |
yield* fiboGen(len - 1, next, current + next); | |
} | |
const fiboGenerator = [...fiboGen(10)] | |
console.log(fiboGenerator) // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment