如何利用 Map 实现固定容量的 LRU 缓存?
参考答案
LRU 在容量不足时淘汰最近最少使用的条目。Map 保留键的插入顺序,可以在命中或更新时先删除再插入,使最新使用的键位于末尾,最早的键作为淘汰候选。
JavaScript
class LRUCache {
constructor(capacity) {
if (!Number.isInteger(capacity) || capacity < 1) {
throw new RangeError('容量必须为正整数');
}
this.capacity = capacity;
this.items = new Map();
}
get(key) {
if (!this.items.has(key)) return undefined;
const value = this.items.get(key);
this.items.delete(key);
this.items.set(key, value);
return value;
}
set(key, value) {
this.items.delete(key);
this.items.set(key, value);
if (this.items.size > this.capacity) {
this.items.delete(this.items.keys().next().value);
}
}
}
这是教学实现,不包含过期时间、并发请求合并或内存字节上限。get 返回 undefined 无法区分“未命中”和“缓存的值就是 undefined”,业务需要时应增加 has 或显式结果结构。