-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoize.js
More file actions
51 lines (32 loc) · 991 Bytes
/
Copy pathMemoize.js
File metadata and controls
51 lines (32 loc) · 991 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
48
49
50
51
// The Problem
// Create a memoize function that takes another function as an argument and
// returns a new version of that function. If the new function is called with
// inputs it has seen before, it should return the cached result instead of
// recalculating it.
const val = new Map();
let arr = [1,2,3,1,3,4,2,1];
val.set(arr)
console.log(val)
function memoize(callback) {
const cache = new Map();
return function (...args) {
const key = JSON.stringify(args);
console.log(key);
// if cache
if (cache.has(key)) {
console.log('Return from Cache')
return key
}
const result = callback(...args);
cache.set(key);
console.log('Setting New Keys')
console.log('entries => ', cache.entries())
return result;
}
}
function sum(a, b) {
return a + b
}
const memoizedValue = memoize(sum);
console.log(memoizedValue(5, 10));
console.log(memoizedValue(5, 10));