js实现RLU算法

RLU

RLU最近最少使用,针对是时间戳,不是使用次数

class RLU {
  constructor(capacity) {
    this.capacity = capacity;
    this.cache = new Map();
  }

  get(key) {
    if (this.cache.has(key)) {
      const value = this.cache.get(key);
      this.cache.delete(key);
      this.cache.set(key, value);
      return value;
    } else {
      return -1;
    }
  }

  put(key, value) {
    if (this.cache.has(key)) {
      this.cache.delete(key);
    } else {
      if (this.cache.size == this.capacity) {
        const firstKey = this.cache.keys().next().value;
        this.cache.delete(firstKey);
      }
    }
    this.cache.set(key, value)
  }

}

const rlu = new RLU(2);
rlu.put('key1', '1')
rlu.put('key2', '2');
rlu.get('key1');
rlu.put('key3', '3')

console.log('rlu', rlu);

你可能感兴趣的:(javascript,前端,开发语言)