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

輸出:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章