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
43 changes: 43 additions & 0 deletions src/memoization/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Fibonacci Function

This module provides a function to compute the nth Fibonacci number using memoization to optimize performance.

## Function

### `fibonacci(position: number): number`

#### Description

Computes the nth Fibonacci number using memoization to optimize performance.

#### Parameters

- `position` (number): The position in the Fibonacci sequence to compute. If a non-negative integer is provided, it will default to 0.

#### Returns

- `number`: The nth Fibonacci number.

#### Example

```typescript
import { fibonacci } from './index'

console.log(fibonacci(0)) // returns 0
console.log(fibonacci(1)) // returns 1
console.log(fibonacci(5)) // returns 5
console.log(fibonacci(10)) // returns 55
```

## Usage

1. Import the `fibonacci` function from the module.
2. Call the function with the desired position in the Fibonacci sequence.

## Notes

- The function uses memoization to store previously computed Fibonacci numbers, which significantly improves performance for large values of `n`.

## License

This project is licensed under the MIT License.
28 changes: 21 additions & 7 deletions src/memoization/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,24 @@
const memo: { [key: number]: number } = {}
const memo: number[] = []

export const fibonacci = (n: number): number => {
if (n <= 0) return 0
if (n === 1) return 1
if (memo[n]) return memo[n]
/**
* Computes the nth Fibonacci number using memoization to optimize performance.
*
* @param {number} n - The position in the Fibonacci sequence to compute. If a non-negative integer is provided, it will default to 0.
* @returns {number} - The nth Fibonacci number.
*
* @example
* ```typescript
* fibonacci(0); // returns 0
* fibonacci(1); // returns 1
* fibonacci(5); // returns 5
* fibonacci(10); // returns 55
* ```
*/
export const fibonacci = (position: number): number => {
if (position <= 0) return 0
if (position === 1) return 1
if (memo[position]) return memo[position]

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