Skip to content

Latest commit

 

History

History
41 lines (37 loc) · 1.18 KB

146-LRU缓存机制.md

File metadata and controls

41 lines (37 loc) · 1.18 KB

146-LRU缓存机制

原题

参考

解法

class LRUCache {
    constructor(capacity, intervalTime) {
        this.cache = new Map();
        this.capacity = capacity;
        this.intervalTime = intervalTime;
    }

    get(key) {
        let tempValue = this.cache.get(key);
        let time = tempValue.time;
        this.cache.delete(key);
        if (Date.now() - time > this.intervalTime) {
            return null;
        }
        this.cache.set(key, {value: tempValue.value, time: Date.now()});
        return tempValue.value;
    }

    put(key, value) {
        if (this.cache.has(key)) {
            this.cache.delete(key);
        }
        if (this.cache.size > this.capacity) {
            const keys = this.cache.keys();
            this.cache.delete(keys.next().value);
        }
        this.cache.set(key, {value: value, time: Date.now()});
    }
}