-
Notifications
You must be signed in to change notification settings - Fork 43
/
dp_demo_1.js
44 lines (39 loc) · 881 Bytes
/
dp_demo_1.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
//learn to cache
function addTo80(n) {
return n + 80;
}
addTo80(5)
let cache = {};
function memoizeAddTo80(n) {
if (n in cache) {
return cache[n];
} else {
console.log('long time');
const answer = n + 80;
cache[n] = answer;
return answer;
}
}
// console.log(1, memoizeAddTo80(6))
// // console.log(cache)
// // console.log('-----------')
// console.log(2, memoizeAddTo80(6))
// let's make that better with no global scope. This is closure in javascript so.
function memoizeAddTo80(n) {
let cache = {};
return function(n) {
if (n in cache) {
return cache[n];
} else {
console.log('long time');
const answer = n + 80;
cache[n] = answer;
return answer;
}
}
}
const memoized = memoizeAddTo80();
console.log(1, memoized(6))
// console.log(cache)
// console.log('-----------')
console.log(2, memoized(6))