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()

posted @ 2022-02-21 14:33  Samsara315  阅读(217)  评论(0编辑  收藏  举报