JavaScript 的 LRU缓存实现

等级 5546 次按键

LRU缓存在超过容量时淘汰最近最少使用的项。

JavaScript 代码

// 使用Map的LRU(最近最少使用)缓存
1class LRUCache {
2 constructor(capacity) {
// 设置最大项数
3 this.capacity = capacity;
// Map保持插入顺序
4 this.cache = new Map();
5 }
6 get(key) {
// 如果键不存在返回-1
7 if (!this.cache.has(key)) return -1;
// 获取值
8 const val = this.cache.get(key);
// 通过重新插入移动到末尾(最近使用)
9 this.cache.delete(key);
10 this.cache.set(key, val);
11 return val;
12 }
13 put(key, value) {
// 如果存在则删除(更新位置)
14 this.cache.delete(key);
// 添加到末尾(最近使用)
15 this.cache.set(key, value);
// 如果超过容量,删除最旧(第一个)项
16 if (this.cache.size > this.capacity) {
// keys().next().value是第一个(最旧的)键
17 this.cache.delete(this.cache.keys().next().value);
18 }
19 }
20}
21
// 创建容量为2的缓存
22const cache = new LRUCache(2);
// 添加项
23cache.put(1, "a"); cache.put(2, "b");
// 获取1(使其成为最近使用)
24console.log(cache.get(1));
// 添加3,淘汰2(最近最少使用)
25cache.put(3, "c");
// 2被淘汰,返回-1
26console.log(cache.get(2));

运行结果

a
-1
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 JavaScript 代码中需要输入的符号及其出现次数。

  • .× 30
  • (× 23
  • )× 23
  • ;× 16
  • ,× 6
  • "× 6
  • {× 5
  • }× 5
  • =× 4
  • -× 1

JavaScript 等级 5 的更多代码示例

← 返回 JavaScript 打字练习