定义
LRU( least recently used)根据数据的历史记录来淘汰数据,重点在于保护最近被访问/使用过的数据,淘汰现阶段最久未被访问的数据
LRU:如果数据最近被访问过,那么将来被访问的几率也更高
实现思路
采用es6的Map
- 新数据插入到链表尾部
- 每当缓存命中(即缓存数据被访问),则将数据移到链表尾部
- 当链表满的时候,将链表头部的数据丢弃
代码展示
class LRUCache {
constructor(limit) {
this.limit = limit
this.cache = new Map()
}
get(key) {
if (this.cache.has(key)) {
// 访问到的 key 若在缓存中,将其提前
const temp = this.cache.get(key)
this.cache.delete(key)
this.cache.set(key, temp)
return temp
}
return -1
}
put(key, value) {
// 存在则删除
if (this.cache.has(key)) {
this.cache.delete(key)
// 超过缓存长度,淘汰最近没使用的
} else if (this.cache.size >= this.limit) {
this.cache.delete(this.cache.keys().next().value)
console.log(`key:${key}, value: ${value}`)
}
// 重新设置
this.cache.set(key, value)
}
toString() {
console.log('limit:', this.limit)
console.table(this.cache)
}
}
const lru = new LRUCache(4)
lru.put(2,2) // 入 2,剩余容量3
lru.put(3,3) // 入 3,剩余容量2
lru.put(4,4) // 入 4,剩余容量1
lru.put(5,5) // 入 5,已满 从头至尾 2-3-4-5
lru.put(4,4) // 入4,已存在 ——> 置队尾 2-3-5-4
lru.put(1,1) // 入1,不存在 ——> 删除队首 插入1 3-5-4-1
lru.get(3) // 获取3,刷新3——> 置队尾 5-4-1-3
lru.toString()