odin-default-js-exercises/10_fibonacci/solution/fibonacci-solution.js

26 lines
591 B
JavaScript
Raw Normal View History

const fibonacci = function(count) {
if (count < 0) return "OOPS";
if (count === 0) return 0;
let firstPrev = 1;
let secondPrev = 0;
for (let i = 2; i <= count; i++) {
let current = firstPrev + secondPrev;
secondPrev = firstPrev;
firstPrev = current;
}
return firstPrev;
2022-02-20 19:07:44 +00:00
};
// Another way to do it is by using an iterative approach with an array containing two values, 0 and 1.
// const fib = [0, 1];
// for (let i = 2; i <= count; i++) {
// fib[i] = fib[i - 1] + fib[i - 2];
// }
// return fib[count];
2022-02-20 19:07:44 +00:00
module.exports = fibonacci;