技术文摘
面试官:如何用 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 编程能力和解决实际问题具有重要意义。希望上述实现方式能够帮助您在面对相关面试问题或实际开发场景时游刃有余。
- 在 Ubuntu Linux 上安装 MongoDB 社区版的方法
- 七款鲜为人知却实用的 Linux 命令行工具 - 移动·开发技术周刊第 211 期
- Android 单元测试:Sqlite、SharedPreference、Assets 及文件操作的测试方法
- 跨浏览器 JavaScript 单元测试的简易解决方案
- 12 种助力高效工作的热门编程语言,你掌握几种?
- 深入剖析 React 源码
- 自主实现小型路由:基于 pushState、popState 与 location.hash 等方法
- PHP十六个魔术方法详细解析
- 深入剖析闭包的多层级内涵
- Redux 异步方案的选择
- VR 与 AR 推动移动 OLED 面板发展的技术力量
- 五大新型 Python 框架带来飞速体验
- 前端中 Cookie 的实践应用
- PHP 与 Go 协程的并发融合
- 《JavaScript 闯关记:基本包装类型》