← 中文资源

简体中文版本

基于 Map 顺序的 LRU 缓存

实现最近最少使用缓存,容量超限时淘汰最旧条目,利用 Map 的插入顺序跟踪访问新旧。

阅读英文原文

实现说明

基于 Map 顺序的 LRU 缓存可以归结为类 LruCache。 代码不会带着坏状态静默继续,守卫一命中就抛 RangeError。

使用要点

  • 守卫 capacity <= 0 命中后立刻用提前的 throw 结束这一轮。
  • 值得导入的表面是 LruCache;周围的辅助代码对片段是私有的。

常见问题

前置条件不成立会发生什么?

校验先行——RangeError 标记失败(位于 capacity <= 0),不会先做一半再失败。

不安装任何包也能运行吗?

可以,开箱即跑——没有引用任何内建 API 之外的东西。

核心语句

if (capacity <= 0) throw new RangeError("capacity must be positive");
if (!this.entries.has(key)) return undefined;
this.entries = new Map();

代码示例

export class LruCache {
  constructor(capacity) {
    if (capacity <= 0) throw new RangeError("capacity must be positive");
    this.capacity = capacity;
    this.entries = new Map();
  }

  get(key) {
    if (!this.entries.has(key)) return undefined;
    const value = this.entries.get(key);
    this.entries.delete(key);
    this.entries.set(key, value);
    return value;
  }

  set(key, value) {
    if (this.entries.has(key)) this.entries.delete(key);
    this.entries.set(key, value);
    if (this.entries.size > this.capacity) {
      const oldest = this.entries.keys().next().value;
      this.entries.delete(oldest);
    }
  }
}