Wiki Elegant

Instances of the Fibonacci Sequence

Create a function that takes a number as an argument and returns n instances of the Fibonacci sequence as an array.

Fibonacci numbers: F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1. So the easy explanation is: The next element is the sum of the two previous elements.

If you want to read more about this sequence, take a look at the On-Line Encyclopedia of Integer Sequences. Fibonacci numbers are strongly related to the golden ratio. See the OEIS and Wikipedia links in the resources tab.

Examples

fibSeq(4) ➞ [0, 1, 1, 2]

fibSeq(7) ➞ [0, 1, 1, 2, 3, 5, 8]

fibSeq(0) ➞ []

Notes

  • If 0 is given, return an empty array.
  • If no argument is given, return undefined.
  • The input will never be a negative integer.
Answer (1)
const fibonacci = n => (n <= 1 ? n : fibonacci(n 1) + fibonacci(n 2));

const fibSeq = length =>
typeof length !== number
? undefined
: Array.from({ length }, (_, i) => fibonacci(i));
Answer (2)
const fibSeq = end => {
if(end === 0) return [];
else if(end === 1) return [0];
else if(end > 1){
let arr = Array.from({length: end});
arr[0] = 0; arr[1] = 1;
for(let i = 2; i < arr.length; i++){
arr[i] = arr[i 1] + arr[i 2];
}
return arr;
}
return undefined;
}
Answer (3)
function fibSeq(end) {
let fibArr = []
let lastNum = 0, sum = 1, temp;
while (end > 0){
temp = sum
sum = lastNum + sum
fibArr.push(lastNum)
lastNum = temp
end
}
return end>=0 ? fibArr : undefined
}
Answer (4)
function fibSeq(end) {
if (end === 0) return [];
if (!end) return undefined;
let fib = [0, 1];
for (i = 2; i < end; i++){
fib[i] = fib[i 2] + fib[i 1];
}
return end === 1 ? fib.slice(0, 1) : fib
}
Answer (5)
function fibSeq(end = null) {
let [sequence, index, a, b] = [[], 0, 0, 1];
while (index < end) {
sequence.push(a);
[a, b] = [b, a + b];
index++;
}
return end === null ? undefined : sequence;
}
Answer (6)

function fibSeq(end) {
if (end === undefined) return undefined;
const fibArr = [];
const fibNum = (num) => fibArr[num 1] + fibArr[num 2];
for (let i = 0; i < end; i++) {
i <= 1 ? fibArr.push(i) : fibArr.push(fibNum(i));
}
return fibArr;
}
Answer (7)
function fibSeq(end) {
if (end === undefined) return undefined;
 
const fibArr = [];
const fibNum = (num) => fibArr[num 1] + fibArr[num 2];
for (let i = 0; i < end; i++) {
i <= 1 ? fibArr.push(i) : fibArr.push(fibNum(i));
}
 
return fibArr;
}
Answer (8)
function fibSeq(num) {
let result = [];
let first = 0;
let second = 1;
for (let i = 0; i < num; i++) {
if (i <= 1) {
result.push(i);
} else {
let next = first + second;
first = second;
second = next;
result.push(next);
}
}
return result;
}
Answer (9)
function fibSeq(n) {
let arr = [0, 1];
for (let i = 2; i < n; i++){
arr.push(arr[i1] + arr[i2]);
}
return arr.slice(0,n);
}
Answer (10)


function fibSeq(n) {
if (n === 0) return []
let fibArr = [0, 1]
while (fibArr.length < n) {
fibArr.push(fibArr[fibArr.length 1] + fibArr[fibArr.length 2])
}
return fibArr
}