-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
4345e0f
commit cb9a1bc
Showing
2 changed files
with
74 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
// Option 1 | ||
export const fibonacci = (n: number) => { | ||
const result = [0, 1]; | ||
|
||
for (let i = 2; i <= n; i++) { | ||
const a = result[i - 1]; | ||
const b = result[i - 2]; | ||
|
||
result.push(a + b); | ||
} | ||
|
||
return result[n]; | ||
}; | ||
|
||
const memoize = (fn: (n: number) => number) => { | ||
const cache: { [key: string]: number } = {}; | ||
|
||
return function (...args: number[]) { | ||
const key = JSON.stringify(args); | ||
|
||
if (cache[key]) { | ||
return cache[key]; | ||
} | ||
|
||
const result = fn.apply(this, args); | ||
cache[key] = result; | ||
|
||
return result; | ||
}; | ||
}; | ||
|
||
const slowFib = (n: number) => { | ||
if (n < 2) { | ||
return n; | ||
} | ||
|
||
return memoizedFib(n - 1) + memoizedFib(n - 2); | ||
}; | ||
|
||
// Option 2 | ||
export const memoizedFib = memoize(slowFib); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import { fibonacci, memoizedFib } from '../fibonacci'; | ||
|
||
describe('Fibonacci Algorithm', () => { | ||
test('Fib function is defined', () => { | ||
expect(typeof fibonacci).toEqual('function'); | ||
expect(typeof memoizedFib).toEqual('function'); | ||
}); | ||
|
||
test('calculates correct fibonacci value for 1', () => { | ||
expect(fibonacci(1)).toEqual(1); | ||
expect(memoizedFib(1)).toEqual(1); | ||
}); | ||
|
||
test('calculates correct fibonacci value for 2', () => { | ||
expect(fibonacci(2)).toEqual(1); | ||
expect(memoizedFib(2)).toEqual(1); | ||
}); | ||
|
||
test('calculates correct fibonacci value for 3', () => { | ||
expect(fibonacci(3)).toEqual(2); | ||
expect(memoizedFib(3)).toEqual(2); | ||
}); | ||
|
||
test('calculates correct fibonacci value for 4', () => { | ||
expect(fibonacci(4)).toEqual(3); | ||
expect(memoizedFib(4)).toEqual(3); | ||
}); | ||
|
||
test('calculates correct fibonacci value for 15', () => { | ||
expect(fibonacci(39)).toEqual(63245986); | ||
expect(memoizedFib(39)).toEqual(63245986); | ||
}); | ||
}); |