LRU(Least Recently Used,最近最少使用)算法根据数据的历史访问记录来进行淘汰数据。核心思想是如果数据最近被访问过,那么将来被访问的几率也会高。
实现代码如下:
class LRUCache {
constructor(size){
this.cache = new Map()
this.size = size || 10
}
}
LRUCache.prototype.get = function (key) {
if (this.cache.has(key)) {
// 存在即更新
let value = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, temp);
return value;
}
return null;
};
LRUCache.prototype.put = function (key, value) {
if (this.cache.has(key)) {
// 存在即更新(删除后加入)
this.cache.delete(key);
} else if (this.cache.size >= this.size) {
// 不存在即加入
// 缓存超过最大值,则移除最近没有使用的
this.cache.delete(this.cache.keys().next().value);
}
this.cache.set(key, value);
};
原文:https://www.cnblogs.com/zhenjianyu/p/13069013.html