js 实现 LRU缓存

LRU是Least Recently Used的缩写,即最近最少使用,是一种常见的缓存置换算法,淘汰最久未使用的数据。原文地址

实现思路

  1. 设定缓存的最大数据量maxSize

  2. 数据按照最近访问时间进行排序,最近访问的数据放在最后

  3. 访问时若数据存在则将数据移动到最后

  4. 添加数据时:

    1. 数据存在,则移动到最后
    2. 不存在,若队列中数据量已到最大值,删除第一个数据,再添加新数据;否则直接添加新数据

代码

由于Map中的数据根据插入的时间具有先后顺序,所以这里使用map来实现;测试地址

class LRU {
  queue = new Map();

  constructor(capacity = 10) {
    // 设置容量
    this.capacity = capacity;
  }

  // 获取数据
  get(key) {
    if (this.queue.has(key)) {
      const value = this.queue.get(key);
      this.queue.delete(key);
      this.queue.set(key, value);
      return value;
    }
    return undefined;
  }

  // 添加数据, 如果存在则移动位置;若数据已经满了,删除第一个元素后再添加
  put(key, value) {
    if (this.queue.has(key)) {
      this.queue.delete(key);
      this.queue.set(key, value);
      return;
    }

    if (this.queue.size >= this.capacity) {
      this.removeFirstItem();
    }
    this.queue.set(key, value);
  }

  // 删除第一个元素
  removeFirstItem() {
    if (this.queue.size) {
      this.queue.delete(this.queue.keys().next().value);
    }
  }
  // 删除数据
  remove(key) {
    if (this.queue.has(key)) {
      this.queue.delete(key);
    }
  }
}
1. 来测试一把,设置容量为4:
const lru = new LRU(4);
lru.put(1, 1);
lru.put(2, 2);
lru.put(3, 3);
console.log([...lru.queue.values()]);

输出:

[1, 2, 3]
2. 读取数据:
const lru = new LRU(4);
lru.put(1, 1);
lru.put(2, 2);
lru.put(3, 3);
lru.get(1);
console.log([...lru.queue.values()]);

输出:

[2, 3, 1]

现在1现在在最后了。

3. 当数据超过容量后再插入数据
const lru = new LRU(4);
lru.put(1, 1);
lru.put(2, 2);
lru.put(3, 3);
lru.put(4, 4);
lru.put(5, 5);
console.log([...lru.queue.values()]);

输出:

 [2, 3, 4, 5]

数据1被删除了.

结束语

上面就是一个简单版的LRU缓存实现,当然在实际使用中还需要结合自身的业务进行调整。
如果是在react中使用,可以使用我的hook版本useLRU

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值