-
Notifications
You must be signed in to change notification settings - Fork 1
/
memoizeFunction.js
49 lines (43 loc) · 1.19 KB
/
memoizeFunction.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function memo(func, resolver) {
// your code here
const cache = new Map();
// Map<cacheKey, Map<context, value>>
return function () {
const cacheKey = resolver
? resolver(...arguments)
: Array.from(arguments).join(",");
const contextMap = cache.get(cacheKey);
// If there is a corresponding context map to cachekey
// Check if context is in the map, if so, return value.
// Else if no corresponding add contextMap, add new entry to the context map
if (!contextMap) {
const value = func.apply(this, arguments);
return value;
}
if (contextMap.has(this)) {
return contextMap.get(this);
} //
// If context not in the map, calculate and add to context map.
const value = func.apply(this, arguments);
contextMap.set(this, value);
return value;
};
}
function testThis(a) {
return `${this.val}_${a}`;
}
const memoFunc = memo(testThis);
const testSubject = {
val: 1,
memo: memoFunc,
};
const testSubject2 = {
val: 2,
memo: memoFunc,
};
// 1_1
console.log(testSubject.memo(1));
// Expected no caching and output is 2_1
console.log(testSubject2.memo(1));
// Expected to cache
console.log(testSubject2.memo(1));