* 每个数组元素是一个对象,{k:v},k->key,v->value
* key可看为是块号,value可看为是块中的内容
* 块号可相同,但块中的内容则不一定相同
*/
function LRUcache(size)
{
this.size = typeof size === "number" ? size : 0;
if(this.size)
{
this.elements = new Array();
}
}
*flag = 0,不存在,flag = 1 存在
*/
LRUcache.prototype.add = function(key,value){
var i,
flag = 0,
len = this.elements.length,
key = typeof key === "number" ? key : -1;
if(key != -1)
{
for(i = 0;i < len; i++)
{
if(this.elements[i].k == key)
{
for(j = i ;j < len - 1; j++)
this.elements[j] = this.elements[j + 1];
this.elements[j] = {k:key,v:value};
flag = 1;
}
}
if(!flag)
{
if(len == this.size)
{
this.elements.shift();
}
this.elements.push({k:key,v:value});
}
return true;
}
return false;
};
LRUcache.prototype.get = function(key){
var i,
len = this.elements.length,
key = typeof key == "number" ? key : -1;
if(key != -1)
{
for(i = 0; i < len; i++)
{
if(this.elements[i].k == key)
{
var tmp = this.elements[i].v;
for(j = i ;j < len - 1; j++)
this.elements[j] = this.elements[j + 1];
this.elements.pop();
return tmp;
}
}
}
return -1;
};
测试用例:
var l = new LRUcache(3);
l.add(3,1);
l.add(5,2);
l.add(1,3);
l.add(2,4);
l.add(3,5);
l.add(1,6);
l.add(5,7);
l.add("5",8);
for(var i = 0, len = l.elements.length; i < len; i++)
console.log(l.elements[i]);
console.log(l.get(1));
console.log(l.get("a"));
console.log(l);