Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions fibonacci.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// fibonacci.js
/**
* Generates a Fibonacci sequence up to the given number of terms.
* @param {number} n - Number of terms to generate (must be ≥ 1)
* @returns {number[]} An array containing the Fibonacci sequence.
*/
function generateFibonacci(n) {
// Validate the input: must be a positive integer (no strings, decimals, or negatives)
if (typeof n !== 'number' || n <= 0 || !Number.isInteger(n)) {
throw new Error('Input must be a positive integer');
}


// Start the sequence with the first Fibonacci number
const sequence = [0];

// If user only wants 1 term, return [0]
if (n === 1) return sequence;

// Add the second Fibonacci number (1)
sequence.push(1);

// Generate the rest of the sequence from index 2 up to n
for (let i = 2; i < n; i++) {

// Each number is the sum of the two before it
const next = sequence[i - 1] + sequence[i - 2];
sequence.push(next);
}
return sequence;
}

module.exports = generateFibonacci;

14 changes: 14 additions & 0 deletions fibonacci.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// fibonacci.test.js
const generateFibonacci = require('./fibonacci');

test('generates the first 5 Fibonacci numbers', () => {
expect(generateFibonacci(5)).toEqual([0, 1, 1, 2, 3]);
});

test('returns only [0] for n = 1', () => {
expect(generateFibonacci(1)).toEqual([0]);
});

test('throws an error for non-integer input', () => {
expect(() => generateFibonacci('five')).toThrow('Input must be a positive integer');
});
Loading