odin-javascript-exercises/10_fibonacci/fibonacci.js

20 lines
384 B
JavaScript
Raw Permalink Normal View History

2023-06-19 17:15:07 -07:00
const fibonacci = function (index) {
if (index < 0) return 'OOPS'
2017-08-25 12:29:48 -07:00
2023-06-19 17:15:07 -07:00
// in loop, add up the sequence until the length of the array is index - 1
let seq = [1]
while (seq.length < index) {
if (seq.length === 1) {
seq.push(1)
} else {
seq.push(seq.at(-1) + seq.at(-2))
}
}
return seq.pop()
}
2017-08-25 12:29:48 -07:00
// Do not edit below this line
2023-06-19 17:15:07 -07:00
module.exports = fibonacci