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
27 changes: 27 additions & 0 deletions Maths/FibonacciIterative.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* @function fibonacciIterative
* @description Returns the nth Fibonacci number using an iterative approach.
* The Fibonacci sequence starts with 0 and 1, and each subsequent number
* is the sum of the two preceding ones: 0, 1, 1, 2, 3, 5, 8, 13, ...
* @param {number} n - The position in the Fibonacci sequence (0-indexed)
* @returns {number} - The nth Fibonacci number
* @see https://en.wikipedia.org/wiki/Fibonacci_sequence
* @example fibonacciIterative(0) => 0
* @example fibonacciIterative(6) => 8
* @example fibonacciIterative(10) => 55
*/
const fibonacciIterative = (n) => {
if (!Number.isInteger(n) || n < 0) {
throw new TypeError('Input must be a non-negative integer')
}
if (n === 0) return 0
if (n === 1) return 1
let a = 0
let b = 1
for (let i = 2; i <= n; i++) {
;[a, b] = [b, a + b]
}
return b
}

export { fibonacciIterative }
39 changes: 39 additions & 0 deletions Maths/test/FibonacciIterative.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { fibonacciIterative } from '../FibonacciIterative.js'

describe('fibonacciIterative', () => {
test('fibonacciIterative(0) returns 0', () => {
expect(fibonacciIterative(0)).toBe(0)
})

test('fibonacciIterative(1) returns 1', () => {
expect(fibonacciIterative(1)).toBe(1)
})

test('fibonacciIterative(2) returns 1', () => {
expect(fibonacciIterative(2)).toBe(1)
})

test('fibonacciIterative(5) returns 5', () => {
expect(fibonacciIterative(5)).toBe(5)
})

test('fibonacciIterative(6) returns 8', () => {
expect(fibonacciIterative(6)).toBe(8)
})

test('fibonacciIterative(10) returns 55', () => {
expect(fibonacciIterative(10)).toBe(55)
})

test('fibonacciIterative(20) returns 6765', () => {
expect(fibonacciIterative(20)).toBe(6765)
})

test('throws TypeError for negative input', () => {
expect(() => fibonacciIterative(-1)).toThrow(TypeError)
})

test('throws TypeError for float input', () => {
expect(() => fibonacciIterative(1.5)).toThrow(TypeError)
})
})
Loading