mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
46 lines
1.1 KiB
JavaScript
46 lines
1.1 KiB
JavaScript
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
|
|
*/
|