LRU缓存函数实现

📅 2026/7/28 13:51:31 👁️ 阅读次数 📝 编程学习
LRU缓存函数实现

LRU Cache直接翻译就是“最不经常使用的数据,重要性是最低的,应该优先删除”。

/*** LRU 缓存(Least Recently Used)* 当缓存容量达到上限时,优先淘汰最久未被使用的数据*/class LRUCacheMap {constructor(capacity) {this.capacity = capacity // 初始化最大缓存数据条数nthis.cache = new Map() // 初始化缓存空间map
                }get(domain) {if (!this.cache.get(domain)) return falseconst info = this.cache.get(domain)this.cache.delete(domain)this.cache.set(key, info)return info}put(domain, info) {if (this.cache.has(domain)) {this.cache.delete(domain) // 移除数据this.cache.set(domain, info) // 在末尾重新插入数据return}// 超出容量则淘汰 Map 头部(最旧)的键if (this.cache.size > this.capacity) {const oldestKey = this.cache.keys().next().valuethis.cache.delete(oldestKey)}this.cache.set(domain, info) // 写入数据
                }print() {console.log([...this.cache.entries()])}}