Keep-alive原理及LRU算法

297 阅读1分钟

Keep-alive实际是vue内部实现的一个组件,内部通过一个对象来缓存组件的vnode,通过一个数组来缓存组件的name或者tag,包含3个参数 include`` excludemax,使用LRU算法来实现,include和exclude可以是字符串、正则、数组类型,匹配vue页面的name,当include和exclude包含同一个name时,include优先级较高,当缓存的组件超过max时,会删除第一个不常用的组件。当匹配到页面时,页面会增加两个钩子,activated和deactivated。 LRU算法题目leetcode.cn/problems/lr…

class LRUCache {
    capacity: number;
    keys: Array<number>;
    caches: Record<number, number>;
    constructor(capacity: number) {
        this.capacity = capacity;
        this.keys = [];
        this.caches = {};
    }

    get(key: number): number {
        if (typeof this.caches[key] != "undefined") {
            this.remove(key);
            return this.caches[key];
        }
        return -1;
    }

    put(key: number, value: number): void {
        if (typeof this.caches[key] != "undefined") {
            this.caches[key] = value;
            this.remove(key);
        } else {
            this.caches[key] = value;
            this.keys.push(key);
            if (this.keys.length > this.capacity) {
                delete this.caches[this.keys[0]];
                this.keys.shift();
            }
        }
    }
    remove(key: number): void {
        const index = this.keys.indexOf(key);
        this.keys.splice(index, 1);
        this.keys.push(key);
    }
}
const lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // 缓存是 {1=1}
lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
lRUCache.get(1); // 返回 1
lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
lRUCache.get(2); // 返回 -1 (未找到)
lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
lRUCache.get(1); // 返回 -1 (未找到)
lRUCache.get(3); // 返回 3
lRUCache.get(4); // 返回 4