js簡単LFU実現
1197 ワード
/* ======================================== LFU ======================================== */
function LFUCache(limit){
limit = limit||10;
var _store = []; // {count:1,data:""}
var index = {};
this.get = function(key){
var ind = index[key];
var result = _store[ind];
if(result==null){ //
return null;
}
var count = ++result.count;
var newInd = -1;
for(var i=0;i=newInd){
index[k]=++index[k];
}
}
index[key] = newInd;
return result;
};
this.set = function(key,value){
if(_store.length>=limit){
_store.pop();
}
// count 1
var oneCountIndex = -1;
for(var i=0;i<_store.length var="" if="" onecountindex="" break="">-1){
_store.splice(oneCountIndex,0,item);
for(var k in index){
if(index[k]>=oneCountIndex){
index[k]=++index[k];
}
}
index[key] = oneCountIndex;
}else{
_store.push(item);
index[key] = _store.length-1;
}
};
this.list = function(){
console.log(JSON.stringify(_store));
};
}