memory-cache.js 1.62 KB
/**
 * memoryCache
 * @author: yyq<yanqing.yang@yoho.cn>
 * @date: 2018/07/23
 */

const _ = require('lodash');

function _clearArray(list, key) {
    _.remove(list, (n) => {
        return n === key;
    });
}

function _clearObject(obj, key) {
    delete obj[key];
}

function _getNowTime() {
    return new Date().getTime() / 1000;
}

module.exports = function memoryCache(maxLength = 1000) {
    let cache = {};
    let mapList = [];

    // 获取缓存数据
    this.get = (key) => {
        if (!cache.hasOwnProperty(key)) {
            return;
        }

        let info = cache[key];

        // 校验过期时间
        if (info.exptime && info.exptime - _getNowTime() < 0) {
            this.clear(key);
            return;
        }

        return info.value;
    };

    // 设置缓存数据
    this.set = (key, value, exptime) => {
        cache.hasOwnProperty(key) && _clearArray(mapList, key);

        mapList.push(key);
        cache[key] = {
            value,
            exptime: exptime ? (exptime + _getNowTime()) : 0 // 过期时间
        };

        // 清除老旧数据
        if (mapList.length > maxLength) {
            let len = mapList.length - maxLength;

            for (let i = 0; i < len; i++) {
                _clearObject(cache, mapList.shift());
            }
        }
    };

    // 清除单条缓存数据
    this.clear = (key) => {
        if (cache.hasOwnProperty(key)) {
            _clearArray(mapList, key);
            _clearObject(cache, key);
        }
    };

    // 清除所有缓存数据
    this.clearAll = () => {
        cache = {};
        mapList = [];
    };

    return this;
};