mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
problems(js): add “2622. Cache With Time Limit”
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
3a111bd4cf
commit
6ca5f53327
1 changed files with 46 additions and 0 deletions
46
problems/cache-with-time-limit.js
Normal file
46
problems/cache-with-time-limit.js
Normal file
|
@ -0,0 +1,46 @@
|
|||
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 existing = this.cache.get(key);
|
||||
if (existing) {
|
||||
clearTimeout(existing.ttl);
|
||||
}
|
||||
|
||||
const ttl = setTimeout(() => this.cache.delete(key), duration);
|
||||
this.cache.set(key, { value, ttl });
|
||||
return Boolean(existing);
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {number} key
|
||||
* @return {number} value associated with key
|
||||
*/
|
||||
TimeLimitedCache.prototype.get = function(key) {
|
||||
if (!this.cache.has(key)) {
|
||||
return -1;
|
||||
}
|
||||
return this.cache.get(key).value;
|
||||
};
|
||||
|
||||
/**
|
||||
* @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
|
||||
*/
|
Loading…
Reference in a new issue