Categories
Leetcode

LRU Cache

class LRUCache {
constructor(capacity) {
    this.capacity = capacity;
    this.cache = {};
    this.keys = [];
};

get(key) {
    // if value is already in the cache,
    // reorder keys array and put the key on the end of queue
    let val = this.cache[key];
    if (val !== undefined) {
        this.keys.splice(this.keys.indexOf(key), 1);
        this.keys.push(key);
        return val;
    }

    return -1;
};

put(key, value) {
    let obj = this.cache[key];

    // if key is already in the cache
    // remove key so we can add it on the end later
    if (obj !== undefined) {
        this.keys.splice(this.keys.indexOf(key), 1);
    }

    // if adding key is already over the capacity
    // we are going to remove the first item on the keys
    if (obj === undefined && this.keys.length === this.capacity) {
        const oldKey = this.keys.shift(); //?
        delete this.cache[oldKey]; //?
    }

    // add key to the keys, this is either an existing key or a new key
    this.keys.push(key); //?

    this.cache[key] = value;
}