Skip to content

Commit 0af6c0c

Browse files
authored
Merge pull request TheAlgorithms#732 from MrDoomy/feat/memoize-func
Feat: Added Memoize Func
2 parents 90b04ea + 0589fc1 commit 0af6c0c

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

Cache/Memoize.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* Memoize
3+
*
4+
* From [Wikipedia](https://en.wikipedia.org/wiki/Memoization),
5+
* memoization is an optimization technique
6+
* used primarily to speed up computer programs,
7+
* by storing the results of expensive function calls
8+
* and returning the cached result when the same inputs occur again
9+
*
10+
* This function is a first class objects,
11+
* which lets us use it as [Higher-Order Function](https://eloquentjavascript.net/05_higher_order.html)
12+
* and return another function
13+
*
14+
* @param {Function} func Original function
15+
* @returns {Function} Memoized function
16+
*/
17+
export const memoize = (func) => {
18+
// Initialization of a slot to store the function result
19+
const cache = {}
20+
21+
return (...args) => {
22+
// Retrieving the first argument of the function
23+
const [arg] = args
24+
25+
/**
26+
* Checks if the argument is already present in the cache,
27+
* then return the associated value / result
28+
*/
29+
if (arg in cache) {
30+
return cache[arg]
31+
}
32+
33+
/**
34+
* If the argument is not yet present in the cache,
35+
* execute original function and save its value / result in cache,
36+
* finally return it
37+
*/
38+
const result = func(arg)
39+
cache[arg] = result
40+
return result
41+
}
42+
}

Cache/test/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(3628800)
36+
})
37+
})

0 commit comments

Comments
 (0)