Files

35 lines
825 B
JavaScript
Raw Permalink Normal View History

const fibonacci = function(countArg) {
// checks argument's type and makes sure we use
// a number throughout rest of function.
let count
if (typeof countArg !== 'number') {
count = parseInt(countArg)
} else {
count = countArg
}
2023-07-04 12:07:04 -05:00
if (count < 0) return "OOPS";
2023-09-18 23:01:33 +02:00
if (count == 0) return 0;
2023-07-04 12:07:04 -05:00
2023-07-05 09:15:36 -05:00
let firstPrev = 1;
let secondPrev = 0;
2023-07-04 12:07:04 -05:00
for (let i = 2; i <= count; i++) {
2023-07-06 09:47:20 -05:00
let current = firstPrev + secondPrev;
2023-07-05 09:15:36 -05:00
secondPrev = firstPrev;
2023-07-06 09:47:20 -05:00
firstPrev = current;
2023-07-04 12:07:04 -05:00
}
2023-07-05 09:15:36 -05:00
return firstPrev;
2022-02-20 14:07:44 -05: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 14:07:44 -05:00
module.exports = fibonacci;