Skip to content

Commit a13b74e

Browse files
authored
Create Memoize
1 parent 2919098 commit a13b74e

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Memoize

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* @param {Function} fn
3+
*/
4+
/*
5+
Example 1:
6+
7+
Input
8+
"sum"
9+
["call","call","getCallCount","call","getCallCount"]
10+
[[2,2],[2,2],[],[1,2],[]]
11+
Output
12+
[4,4,1,3,2]
13+
*/
14+
function memoize(fn) {
15+
const cache = {};
16+
return function(...args) {
17+
const key = JSON.stringify(args);
18+
if(key in cache){
19+
return cache[key];
20+
}
21+
const result = fn.apply(this, args);
22+
cache[key] = result;
23+
24+
return result;
25+
}
26+
}
27+
28+
29+
/**
30+
* let callCount = 0;
31+
* const memoizedFn = memoize(function (a, b) {
32+
* callCount += 1;
33+
* return a + b;
34+
* })
35+
* memoizedFn(2, 3) // 5
36+
* memoizedFn(2, 3) // 5
37+
* console.log(callCount) // 1
38+
*/

0 commit comments

Comments
 (0)