这并不像你那样有效(用ASCII艺术呢!)想要,但它在简单性和可读性方面弥补了这一点。而且在很多情况下,它会很快。
我需要一个简单的LRU缓存来处理少量昂贵的操作(1秒)。我觉得有关的复制粘贴一些小的代码,而不是引入外在的东西更好,但因为我没有找到我写的:
更新:这是现在很多更有效的(时间和空间),因为我删除了数组,因为Map保持了插入顺序。
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) {
if (this.cache.has(key)) // refresh key
this.cache.delete(key);
else if (this.cache.size == this.max) // evict oldest
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"
感谢,我没有穿过运行。它似乎对我的应用程序来说有太多的花里胡哨的东西(更别提ASP.NET这个词,在我看来这是一个巨大的红旗),但也许我应该再看看它。 – 2009-06-15 15:14:24
+1该实现与ASP.NET无关我认为值得一看 – 2009-07-14 01:12:52