1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-16 16:36:56 +02:00
LeetCode/js/cache-with-time-limit.js
Matej Focko 2351dfd0ee
chore: unwrap one layer
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-12-12 14:36:00 +01:00

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