技术文摘
面试官:如何用 JS 实现 LRU 缓存?
2024-12-31 01:14:15 小编
面试官:如何用 JS 实现 LRU 缓存?
在 JavaScript 中实现 LRU(Least Recently Used)缓存是一个常见的面试问题,也是实际开发中优化性能的重要手段。
LRU 缓存的核心思想是,当缓存容量达到上限时,删除最近最少使用的元素。要实现 LRU 缓存,我们可以使用双向链表和哈希表来共同完成。
创建一个节点类来表示链表中的每个元素。节点包含键、值以及指向前一个节点和后一个节点的指针。
class Node {
constructor(key, value) {
this.key = key;
this.value = value;
this.prev = null;
this.next = null;
}
}
接下来,创建 LRU 缓存类。在类中,我们使用一个哈希表来快速查找节点,以及一个双向链表来维护元素的访问顺序。
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.cache = {};
this.head = new Node(null, null);
this.tail = new Node(null, null);
this.head.next = this.tail;
this.tail.prev = this.head;
}
get(key) {
if (this.cache[key]) {
this.moveToHead(this.cache[key]);
return this.cache[key].value;
}
return -1;
}
put(key, value) {
if (this.cache[key]) {
this.cache[key].value = value;
this.moveToHead(this.cache[key]);
} else {
const newNode = new Node(key, value);
this.addNode(newNode);
this.cache[key] = newNode;
if (Object.keys(this.cache).length > this.capacity) {
const removedNode = this.removeTail();
delete this.cache[removedNode.key];
}
}
}
moveToHead(node) {
this.removeNode(node);
this.addNode(node);
}
removeNode(node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
addNode(node) {
node.next = this.head.next;
node.prev = this.head;
this.head.next.prev = node;
this.head.next = node;
}
removeTail() {
const removedNode = this.tail.prev;
this.removeNode(removedNode);
return removedNode;
}
}
通过以上代码,我们成功实现了一个简单的 LRU 缓存。在实际应用中,根据具体的需求还可以对其进行进一步的优化和扩展。
理解并能够实现 LRU 缓存对于提升 JavaScript 编程能力和解决实际问题具有重要意义。希望上述实现方式能够帮助您在面对相关面试问题或实际开发场景时游刃有余。
- 终于有人向 jQuery 开刀,一键解除项目对其依赖
- 2021 年 TIOBE 9 月榜单公布:Python 距 C 仅 0.16%,或冲击冠军!
- 云原生大数据架构里实时计算维表与结果表的选型实践
- 学会使用 Go 语言 Modules,一篇文章就够
- HarmonyOS 服务卡片之残奥会卡片
- HarmonyOS JS UI 自定义 Icon 组件
- 别再只用 map.put 啦!Java 8 compute 让 Map 操作更便捷
- GitHub 爆火!Python 程序大全即将走红
- 学习这门语言两月,仍困于加减乘除
- 版本历史与代码示例:WebSocket、JSTL
- HarmonyOS 示例中的 TaskDispatcher 线程管理
- 浅析慢速二次算法和快速 HashMap
- Spring Boot 中 Filter 的正确使用方法
- Polytree 随想录
- 深入理解 Node.js 的 Fs 模块:共同设计文件系统