我最近一直在 JS 中练习 DSA,这是我的一个问题的解决方案,该问题与限制在缓存中存储密钥的时间有关。下面是代码及其解决方案。我的输出与预期的不同(忽略第一个空值,我没有在下面添加其控制台登录代码),请帮助我了解可能出现的问题。
function TimeLimitedCache(){
this.cache = {};
this.set = function (key, value, duration) {
let timer;
let result = false;
if(key in this.cache){
clearTimeout(timer);
result = true;
}
this.cache[key] = value;
timer = setTimeout(()=> delete this.cache[key],duration);
return result;
}
this.get = function(key){
return this.cache[key] ? this.cache[key] : -1;
}
this.count = function(){
return Object.keys(this.cache).length;
}
}
const start = new Date().getSeconds();
const tesr = new TimeLimitedCache();
setTimeout(()=>console.log(tesr.set(1,42,50)),start)
setTimeout(()=>console.log(tesr.set(1,50,100)),start+40)
setTimeout(()=>console.log(tesr.get(1)),start+50)
setTimeout(()=>console.log(tesr.get(1)),start+120)
setTimeout(()=>console.log(tesr.get(1)),start+200)
setTimeout(()=>console.log(tesr.count(1)),start+250)
你可以使用一个对象来通过按键来存储计时器
this.timers = {};
并且您不需要在函数(键、值、持续时间)中创建计时器。 记得清除各个按键的超时时间。
this.set = function (key, value, duration) {
let result = false;
if (key in this.cache) {
clearTimeout(this.timers[key]);
result = true;
}
this.cache[key] = value;
this.timers[key] = setTimeout(() => delete this.cache[key], duration);
return result;
}