js实现LRU算法
// 新数据插入到链表尾部;
// 每当缓存命中(即缓存数据被访问),则将数据移到链表尾部
// 当链表满的时候,将链表头部的数据丢弃。
class LRUCache {
constructor(capacity) {
this.capacity = capacity
this.cache = new Map()
}
get(key) {
if (this.cache.has(key)) {
let temp = this.cache.get(key)
//访问到的 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)
//存在则删除,if 结束再提前
} else if (this.cache.size >= this.capacity) {
// 超过缓存长度,淘汰最近没使用的 第一个
this.cache.delete(this.cache.keys().next().value)
console.log(`refresh: key:${key} , value:${value}`)
}
this.cache.set(key, value)
}
toString() {
console.log('capacity', this.capacity)
console.table(this.cache)
}
}
const list = new LRUCache(4)
list.put(2, 2) // 入 2,剩余容量3
list.put(3, 3) // 入 3,剩余容量2
list.put(4, 4) // 入 4,剩余容量1
list.put(5, 5) // 入 5,已满 从头至尾 2-3-4-5
list.put(4, 4) // 入4,已存在 ——> 置队尾 2-3-5-4
list.put(1, 1) // 入1,不存在 ——> 删除队首 插入1 3-5-4-1
list.get(3) // 获取3,刷新3——> 置队尾 5-4-1-3
list.toString()
分类:
Javascript
标签:
JavaScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
2020-02-21 判断wangeidtor中输入框内容为空