-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay-14 (2622. Cache With Time Limit).js
More file actions
49 lines (44 loc) · 1.14 KB
/
Day-14 (2622. Cache With Time Limit).js
File metadata and controls
49 lines (44 loc) · 1.14 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
var TimeLimitedCache = function() {
this.cache = new Map();
};
/**
* @param {number} key
* @param {number} value
* @param {number} time until expiration in ms
* @return {boolean} if un-expired key already existed
*/
TimeLimitedCache.prototype.set = function(key, value, duration) {
if(this.cache.has(key)){
clearTimeout(this.cache.get(key).timeoutId);
}
const timeoutId = setTimeout(() => {
this.cache.delete(key);
}, duration);
const existingKey = this.cache.has(key);
this.cache.set(key,{value, timeoutId});
return existingKey;
};
/**
* @param {number} key
* @return {number} value associated with key
*/
TimeLimitedCache.prototype.get = function(key) {
if(this.cache.has(key)){
const {value} = this.cache.get(key);
return value;
}
return -1;
};
/**
* @return {number} count of non-expired keys
*/
TimeLimitedCache.prototype.count = function() {
return this.cache.size;
}
/**
* 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
*/