sharedmemory
Version:
Cluster Shared Memory
136 lines (94 loc) • 2.31 kB
JavaScript
/* Todo
record = {
key, value, count, expire
}
used = {
0: {
key: record,
key: record
},
1: {
...
}
};
usedLength = {
0: 10,
1: 11,
3: 100
};
usedTail = 0;
expire = linkedlist;
*/
var LinkedList = require('./linkedlist');
var CacheLRU = function(config) {
var self = this;
LinkedList.call(self);
config = config || {};
// default -> 30min | number | undefined => closed
self.__expire__ = config.expire == 'default' ? 30 * 60 * 1000 : config.expire;
// 记录数上限
self.__max__ = config.max || 10000;
// 统计
self.__total__ = 0;
self.__miss__ = 0;
self.__hit__ = 0;
// 根据记录数排序的队列
self.__used__ = {};
self.__usedLen__ = {};
};
CacheLRU.prototype = new LinkedList;
CacheLRU.prototype.set = function(key, value) {
if (typeof value == 'undefined') {
this.remove(key);
}
var self = this;
var __list__ = self.__list__;
var record = __list__[key];
if (!record) {
record = {
key: key,
value: value,
count: 0
};
} else {
record.value = value;
record.count += 1;
this.remove(key);
}
if (self.__expire__) {
record.deadline = Date.now() + self.defaultExpire;
}
this.unshift(record);
};
Cache.prototype.get = function(key) {
var value;
var record = this.__list__[key];
if (record) {
if (record.deadline) {
var now = Date.now();
if (record.deadline < now) {
this.remove(key);
} else {
record.deadline = now + this.defaultExpire;
record.count += 1;
value = record.value;
this.remove(key);
this.__list__[key] = record;
this.unshift(record);
}
} else {
record.count += 1;
value = record.value;
this.remove(key);
this.__list__[key] = record;
this.unshift(record);
}
}
return value;
};
Cache.prototype.usedSet = function(record, oldIndex) {
var self = this;
var __used__ = self.__used__;
var __usedLen__ = self.__usedLen__;
var isNew = typeof oldIndex == 'undefined';
};