技术文摘
面试官:如何用 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 编程能力和解决实际问题具有重要意义。希望上述实现方式能够帮助您在面对相关面试问题或实际开发场景时游刃有余。
- C++ 内部类:封装和模块化的关键力量探究
- 一次.NET 某网络边缘计算系统卡死情况分析
- 这张图让 Vue3 源码清晰呈现 !!!
- 深度剖析!Kafka 与 ZooKeeper 的恩怨情仇
- 使用 10 年后,gRPC 存在哪些不足?
- 七款免费的 IntelliJ IDEA 实用插件
- 10 个 Python 脚本助您轻松实现日常任务自动化
- Python 在财务数据分析中的实战运用
- JavaScript ES15 新特性重磅发布!全网深度详解!
- .NET 6 中 ASP.NET Core 极简 API 的新特性研究
- Nginx 配置全解析:轻松掌控多域名管理实战指南
- Promise 高级技巧八则,助力前端开发腾飞
- 智能个性化推荐系统的设计与实践:你掌握了吗?
- 探秘 Lego:客户端日志系统的发展历程
- ThinkPHP8 框架与 Swoole 集成打造高性能 RPC 服务