-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.ts
57 lines (51 loc) · 1.27 KB
/
solution.ts
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
class TimeLimitedCache {
map = new Map<number, {value:number, expire:number}>()
constructor () {
}
set (key: number, value: number, duration: number): boolean {
this._expire();
const time = Date.now();
const expire = time + duration;
if (this.map.has(key)) {
this.map.set(key, {
value,
expire,
});
return true;
} else {
this.map.set(key, {
value,
expire,
});
return false;
}
}
get (key: number): number {
this._expire();
if (this.map.has(key)) {
return this.map.get(key).value;
} else {
return -1;
}
}
count (): number {
this._expire();
return this.map.size;
}
_expire () {
const keys = [...this.map.keys(), ];
const time = Date.now();
for (const key of keys) {
if (this.map.get(key).expire <= time) {
this.map.delete(key);
}
}
}
}
/**
* Your TimeLimitedCache object will be instantiated and called as such:
* var obj = new TimeLimitedCache()
* obj.set(1, 42, 1000); // false
* obj.get(1) // 42
* obj.count() // 1
*/