cache在项目中的应用

var Cache = function(max, buffer) {
    this.$cache = [];
    this.$max = max | 0 || 20;
    this.$buffer = buffer | 0 || 5;
};
Cache.prototype.set = function(key, cacheItem) {
    var cache = this.$cache;
    key = 'cache_' + key;
    var temp = cache[key];
    if (!cache.hasOwnProperty(key)) {
        if (cache.length >= this.$max + this.$buffer) { //缓存列表和缓冲区都满了
            cache.sort(function(a, b) {
                return b.fre == a.fre ? b.time - a.time : b.fre - a.fre;
            });
            var counter = this.$buffer;
            while (counter--) { //缓冲区有多少,我们就一次性删除多少
                var item = cache.pop();
                delete cache[item.key];
            }
        }
        temp = {};
        cache.push(temp);
        cache[key] = temp;
    }
    temp.item = cacheItem;
    temp.fre = 1;
    temp.key = key;
    temp.time = new Date().getTime();
    return temp;
};

Cache.prototype.get = function(key) {
    key = 'cache_' + key;
    var cache = this.$cache;
    var result;
    if (cache.hasOwnProperty(key)) {
        result = cache[key];
        if (result.fre >= 1) {
            result.fre++;
            result.time = new Date().getTime();
            result = result.item;
        }
    }
    return result;
};

Cache.prototype.has = function(key) {
    key = 'cache_' + key;
    return this.$cache.hasOwnProperty(key);
};

Cache.prototype.del = function(key) {
    key = 'cache_' + key;
    var cache = this.$cache;
    var result = cache[key];
    if (result) {
        result.fre = -1;
        delete result.item;
        delete cache[key];
    }
};

 

转载于:https://www.cnblogs.com/haohaoday/p/3620836.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值