js实现LFU算法

LFU

LFU算法是最近最少使用次数算法,针对的是使用次数;
补充一点:对于相同使用次数应该需要加上时间戳,看他人实现LFU算法都没有考虑这一点。
本文通过全局nextId来表示第几次使用功能;

class LFU {
  constructor(capacity) {
    this.capacity = capacity;
    this.cache = [];
    this.nextId = 1; // 用于表示第几次存储的,区分相同存储次数
  }

  get(key) {
    let value = -1;
    this.cache.some((cache) => {
      if (cache.key == key) {
        value = cache.value;
        cache.count++;
        cache.useId = this.nextId;
        this.nextId++;
        return true;
      }
      return false;
    });
    return value;
  }

  set(key, value) {
    let minCountIndex;
    let hasKey = false;
    for(let i = 0; i<this.cache.length; i++) {
      const item = this.cache[i];
      if (item.key === key) {
        hasKey = true;
        item.value = value;
        item.count++;
        item.useId = this.nextId;
        this.nextId++;
        return;
      }
      
      if (index === 0) {
        minCountIndex = 0;
      } else {
        const minItem = this.cache[minCountIndex];
        if (minItem.count > item.count ||
          (minItem.count === item.count && minItem.useId < item.useId)
          ) {
          minCountIndex = i;
        }
      }

    }

    if (!hasKey) {
      if (this.cache.length == this.capacity) {
        this.cache.splice(minCountIndex, 1);
      }
      this.cache.unshift({key, value, count: 1, useId: this.nextId});
      this.nextId++;
    }
  }

}

const lfu = new LFU(2);

lfu.set('key1', 'value1');
lfu.get('key1');
lfu.set('key2', 'value2');
lfu.set('key3', 'value3');
lfu.set('key4', 'value4');
lfu.get('key4');
console.log('lfu', lfu);

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