-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathSolution.ts
43 lines (36 loc) · 1.02 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
class TimeLimitedCache {
private cache: Map<number, [value: number, expire: number]> = new Map();
constructor() {}
set(key: number, value: number, duration: number): boolean {
this.removeExpire();
const ans = this.cache.has(key);
this.cache.set(key, [value, this.now() + duration]);
return ans;
}
get(key: number): number {
this.removeExpire();
return this.cache.get(key)?.[0] ?? -1;
}
count(): number {
this.removeExpire();
return this.cache.size;
}
private now(): number {
return new Date().getTime();
}
private removeExpire(): void {
const now = this.now();
for (const [key, [, expire]] of this.cache) {
if (expire <= now) {
this.cache.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
*/