JS实现LRU缓存置换算法

在这里插入图片描述

function LRUCache(capacity) {

  this.capacity = capacity//缓存容量
  this.map = {}//记录缓存的节点
  this.list = new DoubleLinkList(this.capacity)//实现双向链表 
 
  //获取使用的节点
  this.get = function (getKey) {
    let flag = false
    //判断缓存中是否有该节点
    for (const key in this.map) {
      if (this.map.hasOwnProperty(key)) {
        //缓存中有该节点 返回节点值 并将该节点提升至链表头部
        if (key == getKey) {
          let node = this.map[key]
          this.list.remove(node)
          this.list.appendFront(node)
          flag = true
          return node.value
        }
      }
    }
    //缓存中没有该节点 返回-1
    if (!flag) {
      return -1
    }
  }
  //向缓存中存放节点
  this.put = function (getKey, value) {
    let flag = false
    //缓存中是否有该节点
    for (const key in this.map) {
      if (this.map.hasOwnProperty(key)) {
        //将节点提升至链表头部
        if (key === getKey) {
          let node = this.map[key]
          this.list.remove(node)
          node.value = value
          this.list.appendFront(node)
          flag = true
          return node.value
        }
      }
    }
    //缓存中不存在该节点
    if (!flag) {
      node = new Node(getKey, value)
      //判断缓存容量是否已满
      if (this.list.size >= this.list.capacity) {
        //删除末尾节点,删除map记录的缓存节点
        let old_node = this.list.remove()
        delete this.map[old_node.key]
      }
      //将节点添加至头部
      this.list.appendFront(node)
      this.map[getKey] = node
    }
  }
  this.print = function () {
    this.list.print()
  }
}

测试:

let cache = new LRUCache(2)
cache.put(1, 1)
cache.print()
cache.put(2, 2)
cache.print()
cache.put(3, 3)
cache.print()
console.log(cache.get(1));
cache.print()
console.log(cache.get(2));
cache.print()

输出:
在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值