Create a TimeLimitedCache class that allows you to get and set key-value pairs, with each key-value pair having an associated expiration time. Specifically, implement three methods:
set(key, value, duration): Accepts an integer key, an integer value, and a duration in milliseconds. After the duration expires, the key-value pair should no longer be accessible. If the key already exists and has not expired, return true, otherwise return false. If the key exists, its value and duration should be overwritten with the new value and duration.get(key): If the key exists and has not expired, return its corresponding value. If the key does not exist or has expired, return 1.count(): Return the total number of keys that exist and have not expired.// Example
Input:
actions = ["TimeLimitedCache", "set", "get", "count", "get"]
values = [[], [1, 42, 100], [1], [], [1]]
timeDelays = [0, 0, 50, 50, 150]
Output: [null, false, 42, 1, -1]
Explanation:
At t=0, create TimeLimitedCache.
At t=0, add (1: 42) with a duration of 100 milliseconds. Since the key 1 does not exist yet, return false.
At t=50, check key=1. Since it has not yet expired (100 milliseconds has not passed), return 42.
At t=50, call count(). There is currently one key (key=1), so return 1.
At t=100, key=1 expires.
At t=150, call get(1). Since the key has expired, return -1.
function TimeLimitedCache(){
this.cache = new Map()
}
TimeLimitedCache.prototype.set = function(key, value, duration) {
const found = this.cache.has(key)
if(found){
clearTimeout(this.cache.get(key).timerId)
}
this.cache.set(key, {
value,
timerId: setTimeout(() => this.cache.delete(key), duration)
})
return found
}
TimeLimitedCache.prototype.get = function(key) {
if(this.cache.has(key)) {
return this.cache.get(key).value
} else {
return -1
}
};
TimeLimitedCache.prototype.count = function() {
return this.cache.size
};
class TimeLimitedCache {
constructor() {
this.cache = new Map()
}
set(key, value, duration) {
const found = this.cache.has(key)
if (found) {
clearTimeout(this.cache.get(key).timerId)
}
this.cache.set(key, {
value, value,
timerId: setTimeout(() => {
this.cache.delete(key)
}, duration)
})
return found
}
get(key) {
return this.cache.has(key) ? this.cache.get(key).value : -1
}
count() {
return this.cache.size
}
}