LRU(Least Recently Used)是一种缓存淘汰策略,它删除最近最少使用的项目以腾出空间。在 JavaScript 中,你可以实现一个 LRU 缓存来管理数据,以便在内存有限的情况下,始终保留最常用的数据。
下面是一个简单的 JavaScript LRU 缓存的实现,它使用 Map 来存储数据,并保持缓存的大小不超过指定的限制:
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.cache = new Map();
}
get(key) {
if (this.cache.has(key)) {
// 将最近访问的数据移到最前面
const value = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, value);
return value;
}
return -1; // 未找到
}
put(key, value) {
if (this.cache.has(key)) {
// 如果 key 存在,更新值,并将其移到最前面
this.cache.delete(key);
} else if (this.cache.size >= this.capacity) {
// 如果缓存已满,删除最旧的数据(最后一个数据)
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
this.cache.set(key, value);
}
}
这个 LRUCache 类实现了一个简单的 LRU 缓存,通过 get 方法获取数据并将数据移到最前面,通过 put 方法添加数据并维护缓存大小不超过指定容量。你可以根据需要将这个基本示例扩展为更复杂的缓存管理器,以满足你的项目需求。
网友评论