在大多数实现平均情况下,地图应该是 O(1)。由于 Map 保持插入顺序,因此在其周围添加一些代码将为您提供 LRU,并且对于大多数用途而言,这应该非常快。
我需要一个简单的 LRU 缓存来执行少量昂贵的操作(1 秒)。我对复制粘贴一些小代码而不是引入外部代码感觉更好,但由于我没有找到它,所以我写了它:
class LRU {
constructor(max = 10) {
this.max = max;
this.cache = new Map();
}
get(key) {
let item = this.cache.get(key);
if (item) {
// refresh key
this.cache.delete(key);
this.cache.set(key, item);
}
return item;
}
set(key, val) {
// refresh key
if (this.cache.has(key)) this.cache.delete(key);
// evict oldest
else if (this.cache.size == this.max) this.cache.delete(this.first());
this.cache.set(key, val);
}
first() {
return this.cache.keys().next().value;
}
}
用法:
> let cache = new LRU(3)
> [1, 2, 3, 4, 5].forEach(v => cache.set(v, 'v:'+v))
> cache.get(2)
undefined
> cache.get(3)
"v:3"
> cache.set(6, 6)
> cache.get(4)
undefined
> cache.get(3)
"v:3"