-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path014 — 2622. Cache With Time Limit.js
More file actions
45 lines (41 loc) · 1.08 KB
/
014 — 2622. Cache With Time Limit.js
File metadata and controls
45 lines (41 loc) · 1.08 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
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) {
const valueInCache = this.cache.get(key);
if(valueInCache) {
clearTimeout(valueInCache.timeout);
}
const timeout = setTimeout(() => this.cache.delete(key), duration)
this.cache.set(key, {
value,
timeout
})
return Boolean(valueInCache)
};
/**
* @param {number} key
* @return {number} value associated with key
*/
TimeLimitedCache.prototype.get = function(key) {
return this.cache.has(key) ? this.cache.get(key).value : -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
*/