lrucache实现 JS
LRU Cache 实现(JavaScript)
LRU(Least Recently Used)缓存是一种常见的缓存淘汰策略,当缓存空间不足时,会优先移除最近最少使用的数据。以下是基于 JavaScript 的实现方案:

使用 Map 实现(ES6)
利用 Map 保持键的插入顺序,结合双向链表的思想实现 LRU:

class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.cache = new Map();
}
get(key) {
if (!this.cache.has(key)) return -1;
const value = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, value); // 更新为最新访问
return value;
}
put(key, value) {
if (this.cache.has(key)) {
this.cache.delete(key);
} else if (this.cache.size >= this.capacity) {
// 删除最久未使用的键(Map 第一个键)
const oldestKey = this.cache.keys().next().value;
this.cache.delete(oldestKey);
}
this.cache.set(key, value);
}
}
双向链表 + 哈希表实现
更高效的 O(1) 时间复杂度实现:
class ListNode {
constructor(key, value) {
this.key = key;
this.value = value;
this.prev = null;
this.next = null;
}
}
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.size = 0;
this.hash = {};
this.head = new ListNode(0, 0);
this.tail = new ListNode(0, 0);
this.head.next = this.tail;
this.tail.prev = this.head;
}
_addNode(node) {
node.prev = this.head;
node.next = this.head.next;
this.head.next.prev = node;
this.head.next = node;
}
_removeNode(node) {
const prev = node.prev;
const next = node.next;
prev.next = next;
next.prev = prev;
}
_moveToHead(node) {
this._removeNode(node);
this._addNode(node);
}
get(key) {
const node = this.hash[key];
if (!node) return -1;
this._moveToHead(node);
return node.value;
}
put(key, value) {
const node = this.hash[key];
if (node) {
node.value = value;
this._moveToHead(node);
} else {
const newNode = new ListNode(key, value);
this.hash[key] = newNode;
this._addNode(newNode);
this.size++;
if (this.size > this.capacity) {
const tail = this.tail.prev;
this._removeNode(tail);
delete this.hash[tail.key];
this.size--;
}
}
}
}
使用场景说明
- Map 实现:适合简单场景,代码简洁但依赖
Map的插入顺序特性(非标准行为,但主流浏览器支持)。 - 双向链表实现:标准 O(1) 操作,适合高频访问场景,如前端路由缓存、API 响应缓存等。
注意事项
- 缓存容量需根据实际内存限制设置。
- 链表实现中需注意节点引用的正确性,避免内存泄漏。
- 在 TypeScript 中可添加泛型支持不同类型的键值。





