实现说明
基于 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);
}
}
}