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: 10 additions & 17 deletions Maths/Fibonacci.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,25 +26,18 @@ const FibonacciGenerator = function* (neg) {
}
}

const list = []
const FibonacciRecursive = (num) => {
const isNeg = num < 0
if (isNeg) num *= -1
return (() => {
switch (list.length) {
case 0:
list.push(0)
return FibonacciRecursive(num)
case 1:
list.push(1)
return FibonacciRecursive(num)
case num + 1:
return list
default:
list.push(list.at(-1) + list.at(-2))
return FibonacciRecursive(num)
const list = num === 0 ? [0] : [0, 1]
const buildSequence = () => {
if (list.length === num + 1) {
return list
}
})().map((fib, i) => fib * (isNeg ? (-1) ** (i + 1) : 1))
list.push(list.at(-1) + list.at(-2))
return buildSequence()
}
return buildSequence().map((fib, i) => fib * (isNeg ? (-1) ** (i + 1) : 1))
}

const dict = new Map()
Expand Down Expand Up @@ -81,8 +74,8 @@ const FibonacciDpWithoutRecursion = (num) => {
const isNeg = num < 0
if (isNeg) num *= -1
const table = [0]
table.push(1)
table.push(isNeg ? -1 : 1)
if (num >= 1) table.push(1)
if (num >= 2) table.push(isNeg ? -1 : 1)
for (let i = 2; i < num; ++i) {
table.push(isNeg ? table[i - 1] - table[i] : table[i] + table[i - 1])
}
Expand Down
20 changes: 20 additions & 0 deletions Maths/test/Fibonacci.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,26 @@ import {
} from '../Fibonacci'

describe('Fibonacci', () => {
it('should build recursive sequences independently of earlier calls', () => {
expect(FibonacciRecursive(6)).toEqual([0, 1, 1, 2, 3, 5, 8])
expect(FibonacciRecursive(2)).toEqual([0, 1, 1])
expect(FibonacciRecursive(8)).toEqual([0, 1, 1, 2, 3, 5, 8, 13, 21])
expect(FibonacciRecursive(1)).toEqual([0, 1])
expect(FibonacciRecursive(-3)).toEqual([-0, 1, -1, 2])
})

it('should return only zero for the recursive sequence at index zero', () => {
expect(FibonacciRecursive(0)).toEqual([0])
})

it.each([
[0, [0]],
[1, [0, 1]],
[-1, [0, 1]]
])('should stop the iterative DP sequence at index %i', (n, expected) => {
expect(FibonacciDpWithoutRecursion(n)).toEqual(expected)
})

it('should return an array of numbers for FibonacciIterative', () => {
expect(FibonacciIterative(6)).toEqual(
expect.arrayContaining([0, 1, 1, 2, 3, 5, 8])
Expand Down