这一题当时写的比较暴力,就是对象key value time的存储方式,然后每次取值和赋值都取一次当前时间去做对比。后来发现用Map
结构来处理这个问题会更优雅一些
/**
* const timeLimitedCache = new TimeLimitedCache()
* timeLimitedCache.set(1, 42, 1000); // false
* timeLimitedCache.get(1) // 42
* timeLimitedCache.count() // 1
*/
题解
var TimeLimitedCache = function() {
this.map = new Map()
this.times = {}
};
// 如果存在一个未过期的键,它应该返回这个键相关的值。否则返回 -1
// 一旦 duration 到期后,这个键就无法访问。如果相同的未过期键已经存在,该方法将返回 true ,否则返回 false 。
// 如果该键已经存在,则它的值和持续时间都应该被覆盖。
TimeLimitedCache.prototype.set = function(key, value, duration) {
const res = this.map.has(key)
// 覆盖原本的对象 key val
this.map.set(key,value)
// 清空定时器
clearTimeout(this.times[key])
// 对key 重新定义定时器
this.times[key] = setTimeout(()=>{
this.map.delete(key)
},duration)
// 存在 true 不存在false
return res
};
TimeLimitedCache.prototype.get = function(key) {
return this.map.get(key) ?? -1 //get不存在返回undefined ??运算符在左侧为undefined或null时去右边值
};
/**
* @return {number} count of non-expired keys
*/
TimeLimitedCache.prototype.count = function() {
return this.map.size
}