LRU缓存淘汰算法

  • 使用map作为数据结构
  • map是有序的,最新添加的在后面。(已存在的可以先删除,再添加)
class LRUCache {
  #limit
  #cache
  constructor(limit) {
    this.#limit = limit
    this.#cache = new Map()
  }
 
  has(key) {
    return this.#cache.has(key)
  }
 
  get(key) {
    if (!this.#cache.has(key)) {
      return
    }
 
    const value = this.#cache.get(key)
    this.#cache.delete(key)
    this.#cache.set(key, value)
 
    return value
  }
 
  set(key, value) {
    if (this.#cache.has(key)) {
      this.#cache.delete(key)
    } else if (this.#cache.size >= this.#limit) {
      const oldestKey = this.#cache.keys().next().value
      this.#cache.delete(oldestKey)
    }
 
    this.#cache.set(key, value)
  }
}