js 簡單實現 LFU

/* ======================================== 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<ind;i++){
			if(_store[i].count<=count){
				newInd = i;
				break;
			}
		}
		// 將命中的元素移動到指定的位置
		_store.splice(ind,1);
		_store.splice(newInd,0,result);

		
		for(var k in index){
			if(index[k]>=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;i++){
			var count = _store[i].count;
			if(count==1){
				oneCountIndex = i;
				break;
			}
		}
		
		var item = {count:1,data:value};
		
		if(oneCountIndex>-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));
	};		
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章