-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy path05-cache.js
45 lines (40 loc) · 1.08 KB
/
05-cache.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
// 05 - Cache with property specific TTL
function cacheObj(ttlFunc) {
const obj = {},
handler = {
get (obj, prop) {
const data = Reflect.get(obj, prop);
if (data) {
return data.value;
}
},
set (obj, prop, value) {
const data = {
ttl: ttlFunc(prop),
value: value
};
return Reflect.set(obj, prop, data);
}
};
// decrease TTL and remove prop when it reaches zero
function invalidate() {
for (let prop in obj) {
obj[prop].ttl -= 1;
if (obj[prop].ttl <= 0) {
delete obj[prop];
}
}
}
window.setInterval(invalidate, 1000);
return new Proxy(obj, handler);
}
// try it out
const cache = cacheObj(prop => 5);
function log(sec) {
console.log(`${sec}s: a = ${cache.a}`);
}
console.clear();
cache.a = 123;
for (let sec = 0; sec < 6; sec += 1) {
window.setTimeout(() => log(sec), sec * 1000);
}