problems(js): add “2622. Cache With Time Limit”

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2023-05-19 00:43:08 +02:00
parent 3a111bd4cf
commit 6ca5f53327
Signed by: mfocko
GPG key ID: 7C47D46246790496

View 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
*/