Skip to content

LRU Cache js code can be more simple and optimized using builtin Map data structure #844

Closed
@aditya1944

Description

@aditya1944

Map stores order of insertion and internally use a doubly-linked list to achieve this.

sample code to demonstrate: get and put time complexity: O(1)

/**
 * @param {number} capacity
 */
var LRUCache = function(capacity) {
    this.capacity = capacity;
    this.cache = new Map();
};

/** 
 * @param {number} key
 * @return {number}
 */
LRUCache.prototype.get = function(key) {
    if(this.cache.has(key)){
            let value = this.cache.get(key);
            this.cache.delete(key);
            this.cache.set(key,value);
            return value;
        }
        else{
            return -1;
        }
};

/** 
 * @param {number} key 
 * @param {number} value
 * @return {void}
 */
LRUCache.prototype.put = function(key, val) {
    if(this.cache.has(key)){
            //refresh the cache
            this.cache.delete(key);
            this.cache.set(key,val);
        }
        else{
            if(this.cache.size===this.capacity){
                this.cache.delete(this.cache.keys().next().value);
            }
            this.cache.set(key,val);
        }
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions