Attempting to generate a Fibonacci sequence that always starts with [0, 1] using basic JS has proven challenging. The current implementation of the function does not properly return the first two items in an array when calling the corresponding n number. For n = 1 and n = 2 exclusively, the function yields undefined. However, for values of n greater than 2, the Fibonacci sequence is generated accurately with the correct number of array items (including elements 0 and 1).
The code snippet in question:
function fibGenerator(n) {
var output = [];
var num1 = 0;
var num2 = 1;
var next;
if (n === 1) {
output = [0];
} else if (n === 2) {
output = [0, 1];
} else {
output = [num1, num2];
for (var count = 2; count < n; count++) {
next = num1 + num2;
num1 = num2;
num2 = next;
output.push(next);
}
return output;
}
}
If anyone can help identify the issue in the code provided, it would be greatly appreciated! Thank you!