What's wrong with this JavaScript code?


  • 0
    D
    /**
     * @param {number} capacity
     */
     
     
    // NOTE: works for most of the cases
    // first failed input has 105 capacity... it's kinda tough to debug what's wrong
    var LRUCache = function(capacity) {
        this.capacity = capacity;
        this.hash = {};
        this.timeHash = {};
        
        this.max = 0;
    };
    
    /** 
     * @param {number} key
     * @return {number}
     */
    LRUCache.prototype.get = function(key) {
        if(!this.hash[key]){
            return - 1;
        }
        
        this.updateExisting(key, this.hash[key].value);
        return this.hash[key].value;
    };
    
    /** 
     * @param {number} key 
     * @param {number} value
     * @return {void}
     */
    LRUCache.prototype.put = function(key, value) {
        
        if(this.hash[key]){
            this.updateExisting(key, value);
        }
        else if(!this.hash[key] && Object.keys(this.hash).length >= this.capacity) {
            this.removeOldest();
            this.addNew(key, value);
        }
        else {
            this.addNew(key, value);
        }
    };
    
    
    LRUCache.prototype.removeOldest = function() {
        let allTimeKeys = Object.keys(this.timeHash).sort(sorter);
        
        delete this.hash[this.timeHash[allTimeKeys[0]]];
        delete this.timeHash[allTimeKeys[0]];
        
        function sorter(a, b){
            if(a < b) return -1;
            else return 1;
        }
            
    };
    
    LRUCache.prototype.updateExisting = function(key, value) {
        delete this.timeHash[this.hash[key].time];
        this.addNew(key, value);
    };
    
    LRUCache.prototype.addNew = function(key, value) {
        let newTime = this.max + 1;
        
        this.hash[key] = {
            value: value,
            time: newTime
        };
        
        this.timeHash[newTime] = key;
        this.max = newTime;
    };
    
    
    /** 
     * Your LRUCache object will be instantiated and called as such:
     * var obj = Object.create(LRUCache).createNew(capacity)
     * var param_1 = obj.get(key)
     * obj.put(key,value)
     */
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.