0
点赞
收藏
分享

微信扫一扫

LUR变形题

兵部尚输 2022-04-16 阅读 165

字节飞书题

思路

  • 设置一个缓存cache用map数据结构存储数据
  • 本题还需要一个定时器的存储用timerMap
  • 最大容量n
  • 过期时间lifetime
  • get方法:先判断右没有该id,没有的return null,有的话先清除定时器,后删除该id对应的值,再新建
  • set方法:先判断右没有该id的值,有的话,删除该id的值同时清除定时器,没有的话,设置值到cache中同时设置定时器,判断是否超过容量,超过就删除最近未访问元素。
class Cache {
    constructor(n, x) {
      this.cache = new Map();
      this.timerMap = new Map();
      this.size = n;
      this.lifetime = x;
    }
  
    get (id) {
      if (!this.cache.has(id)) return null;
  
      const obj = this.cache.get(id);
  
      clearTimeout(this.timerMap.get(id));  // 清除旧的
      this.cache.delete(id);        // 删除后更新,这里也忘了删除
  
      if (obj.oldTime < Date.now()) {
        return null;
      }
  
      this.cache.set(id, {
        object: obj.object,
        oldTime: Date.now() + this.lifetime
      });
      this.clear(id, this.lifetime);  // 创建新的
  
      return obj.object;
    }
  
    set (id, object) {
      if (this.cache.has(id)) {
        this.cache.delete(id);
        // 清除相关的定时器
        clearTimeout(this.timerMap.get(id)) // 清除旧的,应该放在这,因为如果新set的对象不存在,它也不会有定时器
      }
  
      // clearTimeout(this.timerMap.get(id)) // 放在这里的话虽然 clearTimeout(undefined) 不会有问题,但不大合适
  
      this.cache.set(id, {
        object,
        oldTime: Date.now() + this.lifetime
      })
      // 设置自动清除
      this.clear(id, this.lifetime)
  
      if (this.cache.size > this.size) {      // 超出了最大容量
        const _id = this.cache.keys().next().value;
        clearTimeout(this.timerMap.get(_id)) // 清除出队的对象的定时器
        this.cache.delete(_id);
      }
    }
  
    clear (id, timeOut) {
      timerMap.set(id, setTimeout(() => {
        this.map.delete(id)
      }, timeOut))
    }
  }
举报

相关推荐

0 条评论