FIFO、LFU算法的js代码实现

 

FIFO算法

FIFO算法过程比较简单,先进入的数据先出来,这种行为方式就和队列是一样的。存入的时候从队列尾部进入,淘汰数据的时候从队列头部淘汰。取缓存的时候,直接遍历列表。

示意图如下:

FIFO算法流程图

FIFO使用js实现代码如下

function Cache(key, value) {
  this.value = value;
  this.key = key;
}

function FIFO() {
  this.localCache = [];
  this.maxLength = 5;
}

FIFO.prototype.getCache = function(key) {
  for (var i = 0;i < this.localCache.length; i++) {
    if (this.localCache[i].key === key) {
      return this.localCache[i];
    }
  }
  return null;
}

FIFO.prototype.setCache = function(cache) {
  if (this.localCache.length === this.maxLength) {
    this.localCache.shift();
  }

  this.localCache.push(cache);
}

var c1 = new Cache('1', {p: 111});
var c2 = new Cache('2', {p: 222});
var c3 = new Cache('3', {p: 333});
var c4 = new Cache('4', {p: 444});
var c5 = new Cache('5', {p: 555});
var c6 = new Cache('6', {p: 666});

var fifo = new FIFO();

fifo.setCache(c1);
fifo.setCache(c2);
fifo.setCache(c3);
fifo.setCache(c4);
fifo.setCache(c5);

console.log(fifo);

fifo.setCache(c6);

console.log(fifo);

LFU算法

LFU算法是最近最少使用次数算法,和LRU不同点在于LRU是针对时间的,LFU是针对使用频率的。

但是主体思路上和LRU也是一样的,将缓存按照使用次数最高到使用次数最低来排序,加入的新缓存的使用次数为0,并且淘汰的也是使用次数最少。每一次读取缓存的时候,就得改变被找到的缓存的使用次数,并更新数组的排列。

流程示意图如下:

LFU算法流程图

LFU算法的js实现代码如下

function Cache(key, value) {
  this.key = key;
  this.value = value;
}

function LFU() {
  this.localCache = [];
  this.maxLength = 5;
}

LFU.prototype.getCache = function(key) {
  for (var i = 0;i < this.localCache.length; i++) {
    if (this.localCache[i].key === key) {
      var count = ++this.localCache[i].count;
      console.log('count:', count);
      var result = this.localCache[i];
      this.localCache.sort((a, b) => {return  b.count - a.count});
      return result;
    }
  }
  return null;
}

LFU.prototype.setCache = function(cache) {
  if (this.localCache.length === this.maxLength) {
    this.localCache.pop();
  }

  Object.assign(cache, {count: 0});

  this.localCache.push(cache);
}

var c1 = new Cache('1', {p: 111});
var c2 = new Cache('2', {p: 222});
var c3 = new Cache('3', {p: 333});
var c4 = new Cache('4', {p: 444});
var c5 = new Cache('5', {p: 555});
var c6 = new Cache('6', {p: 666});

var lfu = new LFU();

lfu.setCache(c1);
lfu.setCache(c2);
lfu.setCache(c3);
lfu.setCache(c4);
lfu.setCache(c5);

console.log(lfu);

lfu.getCache('4')
lfu.getCache('4')
lfu.getCache('4')
lfu.getCache('4')
lfu.getCache('3')
lfu.getCache('3')
lfu.getCache('1')
console.log(lfu.getCache('1'));


lfu.setCache(c6);

console.log(lfu);

总结

采用js实现确实会简单点,有些方法都被封装了,比如说pop、shift、unshift、sort这些方法,操作数组特别方便。所以这些就导致很多前端,只会数组,算法也只会冒泡。还是好好回归基础。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值