Fibonacci
JavaScript
Easy
Objective
Write a function that returns the first N numbers of the Fibonacci sequence
Requirements
The function should be called
fibonacci
It should take a single number as an argument
The function should return an array containing the first N number of the Fibonacci sequence (starting from 0)
Check your solution
Tests
Function name is fibonacci | |||
fibonacci(1) | Expected: | [0] | |
fibonacci(5) | Expected: | [0,1,1,2,3] | |
fibonacci(8) | Expected: | [0,1,1,2,3,5,8,13] |
Solution
Here's how I would approach this, but keep in mind there might be other ways to solve this problem.
function fibonacci(number) {
// If number is 1, return 0
if (number === 1) {
return [0];
}
// Our base case is 0 and 1
let fib = [0, 1];
// Loop through the array and add the last two numbers
for(let i = 2; i < number; i++) {
fib.push(fib[i-1] + fib[i-2]);
}
return fib;
}
Click to reveal