-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathCacheManager.js
More file actions
61 lines (52 loc) · 1.7 KB
/
CacheManager.js
File metadata and controls
61 lines (52 loc) · 1.7 KB
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
52
53
54
55
56
57
58
59
60
61
class CacheManager {
constructor() {
this.cache = new Map();
this.expirationTimes = new Map();
}
set(key, value, expirationTime) {
this.cache.set(key, value);
const currentTime = Date.now();
const expirationTimestamp = currentTime + expirationTime;
this.expirationTimes.set(key, expirationTimestamp);
}
get(key) {
const currentTime = Date.now();
if (this.expirationTimes.has(key)) {
const expirationTimestamp = this.expirationTimes.get(key);
if (currentTime <= expirationTimestamp) {
return this.cache.get(key);
} else {
this.cache.delete(key);
this.expirationTimes.delete(key);
}
}
return undefined;
}
clearExpired() {
const currentTime = Date.now();
for (const [key, expirationTimestamp] of this.expirationTimes) {
if (currentTime > expirationTimestamp) {
this.cache.delete(key);
this.expirationTimes.delete(key);
}
}
}
clearAll() {
this.cache.clear();
this.expirationTimes.clear();
}
}
const cacheManager = new CacheManager();
cacheManager.set('key1', 'value1', 1000); // 过期时间为1秒
cacheManager.set('key2', 'value2', 5000); // 过期时间为5秒
console.log(cacheManager.get('key1')); // 输出: value1
console.log(cacheManager.get('key2')); // 输出: value2
setTimeout(() => {
console.log(cacheManager.get('key1')); // 输出: undefined,因为已经过期被清除
console.log(cacheManager.get('key2')); // 输出: value2,还未过期
}, 2000);
setTimeout(() => {
cacheManager.clearExpired(); // 清除过期项
console.log(cacheManager.get('key1')); // 输出: undefined
console.log(cacheManager.get('key2')); // 输出: value2
}, 6000);