LRU缓存 js实现

class DLinkNode {
    key = '';
    value = null;
    pre = null;
    next = null;

    constructor(key,value) {
        this.key = key;
        this.value = value;
    }
}

/**
 * 
 * LRU 缓存
 * 
 */

class LRUCache {

    /** LRU缓存容量 */
    capacity = 3;
    /** 内部维护一个map */
    map = new Map();

    /** 键值队列 */
    keyList = [];

    // 至于为什么不使用对象数组存储就是为了减少时间复杂度,数组的话就需要遍历而链表就
    /** 双向链表头节点 哑结点 避免空节点判断 */
    head;
    /** 双向链表尾结点 哑结点 避免空节点判断 */
    tail;

    size = 0;

    constructor(capacity) {
        if(typeof capacity !== 'number') return;
        this.capacity = capacity;
        this.head = new DLinkNode();
        this.tail = new DLinkNode();

        this.head.next = this.tail;
        this.tail.pre = this.head;
    }

    get(key) {
        const node = this.map.get(key);
        if(!node) return -1;

        // 将最近访问的数据移动到头部
        this.moveToHead(node);

        return node.value;
    }

    put(key,value) {
        let node = this.map.get(key);

        if(!node) {
            let newNode = new DLinkNode(key,value);
            // 添加到哈希表
            this.map.set(key,newNode);
            this.addToHead(newNode);
            ++this.size;
            // 当超过容量的时候将链表尾部的数据移除
            if(this.size > this.capacity) {
                // 链表头部是最新的记录,越靠后数据越旧
                let tail = this.removeTail();
                this.map.delete(tail.key);
                --this.size;
            }
        } else {
            // 如果key存在,先通过哈希表定位,再修改value,并移动到头部
            node.value = value;
            this.moveToHead(node);
        }
    }

    /** 将链表上的节点移动到头部 */
    moveToHead(node) {
        this.removeNode(node);
        this.addToHead(node);
    }

    removeNode(node) {
        node.pre.next = node.next;
        node.next.pre = node.pre;
    }

    addToHead(node) {
        node.pre = this.head;
        node.next = this.head.next;
        this.head.next.pre = node;
        this.head.next = node;
    }

    removeTail() {
        let res = this.tail.pre;
        this.removeNode(res);
        return res;
    }
}

const lruCache = new LRUCache(3);

lruCache.put('1','hello');
lruCache.put('2','asdf');
lruCache.put('3','asdfasdf');
lruCache.put('4','4');

console.log(lruCache.get('4'));
console.log(lruCache.get('1'));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值