Skip to content

Commit 028e098

Browse files
committed
Feat: Added Memoize Func
1 parent 877ce46 commit 028e098

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

Cache/Memoize.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Memoize
3+
* @param {Function} fn
4+
* @returns
5+
*/
6+
export const memoize = (func) => {
7+
// eslint-disable-next-line no-console
8+
console.log(`Creating cache for function '${func.name}'`)
9+
10+
const cache = {}
11+
12+
return (...args) => {
13+
const [arg] = args
14+
15+
if (arg in cache) {
16+
// eslint-disable-next-line no-console
17+
console.log(`Reading cache with argument ${arg}`)
18+
19+
return cache[arg]
20+
}
21+
22+
// eslint-disable-next-line no-console
23+
console.log(`Updating cache with argument ${arg}`)
24+
25+
const result = func(arg)
26+
cache[arg] = result
27+
return result
28+
}
29+
}

Cache/__tests__/Memoize.test.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { memoize } from '../Memoize'
2+
3+
const fibonacci = (n) => {
4+
if (n < 2) {
5+
return n
6+
}
7+
8+
return fibonacci(n - 2) + fibonacci(n - 1)
9+
}
10+
11+
const factorial = (n) => {
12+
if (n === 0) {
13+
return 1
14+
}
15+
16+
return n * factorial(n - 1)
17+
}
18+
19+
describe('memoize', () => {
20+
it('expects the fibonacci function to use the cache on the second call', () => {
21+
const memoFibonacci = memoize(fibonacci)
22+
23+
expect(memoFibonacci(5)).toEqual(fibonacci(5))
24+
expect(memoFibonacci(5)).toEqual(5)
25+
expect(memoFibonacci(10)).toEqual(fibonacci(10))
26+
expect(memoFibonacci(10)).toEqual(55)
27+
})
28+
29+
it('expects the factorial function to use the cache on the second call', () => {
30+
const memoFactorial = memoize(factorial)
31+
32+
expect(memoFactorial(5)).toEqual(factorial(5))
33+
expect(memoFactorial(5)).toEqual(120)
34+
expect(memoFactorial(10)).toEqual(factorial(10))
35+
expect(memoFactorial(10)).toEqual(3_628_800)
36+
})
37+
})

0 commit comments

Comments
 (0)