Skip to content
Merged
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,5 @@ Notably, this is an academic exercise. Many of these data structures are redunda
- [Hash Table](./src/hash-table)
- [Binary Search Tree](./src/binary-tree)
- [Binary Heap](./src/binary-heap) (example MIN implementation)
- [AVL Tree](./src/avl-tree)
- [Memoization](./src/memoization/)
2 changes: 2 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ export * from './stack'
export * from './hash-table'
export * from './binary-tree'
export * from './binary-heap'
export * from './avl-tree'
export * from './memoization'
Empty file added src/memoization/README.md
Empty file.
36 changes: 36 additions & 0 deletions src/memoization/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { describe, it, expect } from 'bun:test'
import { fibonacci } from '.'

describe('Fibonacci Value Retrieval', () => {
it('should return 0 for the first index (0) in the Fibonacci sequence', () => {
expect(fibonacci(0)).toBe(0)
})

it('should return 1 for the second index (1) in the Fibonacci sequence', () => {
expect(fibonacci(1)).toBe(1)
})

it('should return 1 for the third index (2) in the Fibonacci sequence, as it is the sum of the two preceding numbers', () => {
expect(fibonacci(2)).toBe(1)
})

it('should return 2 for the fourth index (3) in the Fibonacci sequence, as it is the sum of the two preceding numbers', () => {
expect(fibonacci(3)).toBe(2)
})

it('should return 3 for the fifth index (4) in the Fibonacci sequence, as it is the sum of the two preceding numbers', () => {
expect(fibonacci(4)).toBe(3)
})

it('should return 5 for the sixth index (5) in the Fibonacci sequence, as it is the sum of the two preceding numbers', () => {
expect(fibonacci(5)).toBe(5)
})

it('should assume 0 for negative indices, as the Fibonacci sequence is not defined for negative numbers', () => {
expect(fibonacci(-1)).toBe(0)
})

it('should return 55 for the eleventh index (10) in the Fibonacci sequence, as it is the sum of the two preceding numbers', () => {
expect(fibonacci(10)).toBe(55)
})
})
10 changes: 10 additions & 0 deletions src/memoization/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const memo: { [key: number]: number } = {}

export const fibonacci = (n: number): number => {
if (n <= 0) return 0
if (n === 1) return 1
if (memo[n]) return memo[n]

memo[n] = fibonacci(n - 1) + fibonacci(n - 2)
return memo[n]
}