LRU缓存(JavaScript)

60 阅读1分钟

LRU缓存(JavaScript)

img

img

1. 定义双向链表节点

function DeLinkedNode(key,value){
    this.key = key==null?null:key;
    this.value = value==null?null:value;
    this.next = null;
    this.prev = null;
}

2. 定义双向链表

function DeLinked(){
    this.head = new DeLinkedNode();
    this.tail = new DeLinkedNode();
    this.head.next = this.tail;
    this.tail.prev = this.head;
    this.size = 0;
}
DeLinked.prototype.addToHead = function(node){
    node.next = this.head.next;
    node.prev = this.head;
    this.head.next.prev = node; 
    this.head.next = node;
    this.size++;
}
DeLinked.prototype.moveToHead = function(node) {
    this.removeNode(node);
    this.addToHead(node);
}
DeLinked.prototype.removeTail = function(){
    let res = this.tail.prev;
    this.removeNode(res);
    return res;
}
DeLinked.prototype.removeNode = function(node){
    node.prev.next = node.next;
    node.next.prev = node.prev;
    this.size--;
}

3. 定义LRU缓存

function LRUcache(capacity){
    this.capacity = capacity;
    this.map = new Map();
    this.deLinked = new DeLinked();
    this.size = 0;
}
/*
如果map含有key,则将链表对应的节点移动到头部;
否则返回-1;
*/
LRUcache.prototype.get = function(key){
    let node = this.map.get(key);
    if(node == null){
        return -1;
    }else{
        this.deLinked.moveToHead(node);
        return node.value;
    }
}
/*
如果map含有key,则将链表对应的节点的value设为新的value值,并移动到头部;
否则添加key,value到map中,并将对应的节点加入双向链表的头部中,size++;
   若size>capacity,则删除链表尾部节点,并删除map中对应的key,size--。
*/
LRUcache.prototype.put = function(key,value){
    let node = this.map.get(key);
    if(node == null){
        let newNode = new DeLinkedNode(key, value);
        this.map.set(key, newNode);
        this.deLinked.addToHead(newNode);
        this.size++;
        if(this.size > this.capacity){
            let res = this.deLinked.removeTail();
            this.map.delete(res.key);
            this.size--;
        }
    }else{
        node.value = value;
        this.deLinked.moveToHead(node);
    }
    
}