-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasicMemoize.js
More file actions
47 lines (40 loc) · 950 Bytes
/
Copy pathbasicMemoize.js
File metadata and controls
47 lines (40 loc) · 950 Bytes
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
// basic memoization with few utilities like clear, size, has
function memoize(func) {
const myCache = {}
function memoized(...args) {
const key = args.join(",")
if (key in myCache) {
console.log("from cache")
return myCache[key]
}
const result = func(...args)
myCache[key] = result
console.log("from result")
return result
}
memoized.clear = function () {
for (key in myCache) {
delete myCache[key]
}
console.log('cache now', JSON.stringify(myCache));
}
memoized.size = function () {
return Object.keys(myCache).length
}
memoized.has = function (...args) {
const key = JSON.stringify(args)
return key in myCache
}
return memoized
}
function add(a, b) {
return a + b
}
memoizedAdd = memoize(add)
memoizedAdd(2, 3)
memoizedAdd(2, 3)
memoizedAdd(2, 3)
memoizedAdd.has(2,3)
console.log('size', memoizedAdd.size());
memoizedAdd.clear();
memoizedAdd(2, 3)