Skip to content

Commit 4499be8

Browse files
committed
feat: 🎸 added custom memoize function
1 parent 9accd77 commit 4499be8

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

2024 Prep/polyfills/memoization.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
//* Write a memoization function
2+
3+
function memoize(func) {
4+
// create cache store
5+
const cache = {}
6+
7+
return function (...args) {
8+
// stringify the args
9+
const keys = JSON.stringify(args)
10+
// check if the args are in the cache
11+
if (cache[keys]) {
12+
// if present then call the cached function
13+
console.log('Cache hit!')
14+
return cache[keys]
15+
} else {
16+
// if args not present in cache recall the function
17+
console.log('Cache miss!')
18+
const result = func.apply(this, args)
19+
// add the result in cache, for next calculation
20+
cache[keys] = result
21+
// return result
22+
return result
23+
}
24+
}
25+
}
26+
27+
const memoizeV2 = func => {
28+
const cache = new Map()
29+
return function (...args) {
30+
const key = JSON.stringify(args)
31+
if (cache.has(key)) {
32+
return cache.get(key)
33+
} else {
34+
const result = func(...args)
35+
cache.set(key, result)
36+
return result
37+
}
38+
}
39+
}
40+
41+
function expensiveOperation(n) {
42+
console.log('Calculating...')
43+
return n * 2
44+
}
45+
const memoizedOperation = memoizeV2(expensiveOperation)
46+
47+
console.log(memoizedOperation(5)) // Output: Calculating... \n Cache miss! \n 10
48+
console.log(memoizedOperation(5)) // Output: Cache hit! \n 10
49+
console.log(memoizedOperation(5)) // Output: Cache hit! \n 10
50+
console.log(memoizedOperation(5)) // Output: Cache hit! \n 10
51+
console.log(memoizedOperation(5)) // Output: Cache hit! \n 10

0 commit comments

Comments
 (0)