LRU:Least Recently Used,最近最少使用
js的Map会保持插入顺序,可以基于Map实现LRU
代码实现
class LRUCache {
constructor(length) {
// 容器最大长度
this.length = length;
// 数据容器
this.map = new Map();
}
// 设置
set(key, value) {
// 容量限制
if (this.map.size >= this.length) {
// 等价于:let firstKey = this.map.keys()[0]
let firstKey = this.map.keys().next().value;
this.map.delete(firstKey);
}
// 存在就删除
if (this.map.has(key)) {
this.map.delete(key);
}
// 重新加入
this.map.set(key, value);
}
// 获取
get(key) {
// 不存在
if (!this.map.has(key)) {
return null;
}
// 访问过就重新加入
let value = this.map.get(key);
this.map.delete(key);
this.map.set(key, value);
}
}
测试
let lru = new LRUCache(3);
lru.set("name", "Tom");
lru.set("age", 20);
lru.set("school", "puk");
console.log(lru);
// Map(3) { 'name' => 'Tom', 'age' => 20, 'school' => 'puk' }
lru.set("name", "Tom");
console.log(lru);
// Map(3) { 'age' => 20, 'school' => 'puk', 'name' => 'Tom' }
lru.set("contry", "china");
console.log(lru);
// Map(3) { 'school' => 'puk', 'name' => 'Tom', 'contry' => 'china' }