Search code examples
javascriptcachingsettimeout

setTimeout usage causing solution to fail


I have been recently practicing DSA in JS and here is the solution to one of my problems related to limiting the time to store a key in cache. Below is the code and the solution of it. My output differs from the expected one (ignore the first null, I have not added its console log in code below), please help me understand what can be the issue.

function TimeLimitedCache(){
    this.cache = {};
    
    this.set = function (key, value, duration) {
        let timer;
        let result = false;
        if(key in this.cache){
            clearTimeout(timer);
            result = true;
        }
        this.cache[key] = value;
        timer = setTimeout(()=> delete this.cache[key],duration);
        return result;
    }

    this.get = function(key){
        return this.cache[key] ? this.cache[key] : -1;
    }

    this.count = function(){
        return Object.keys(this.cache).length;
    }
    
}

const start = new Date().getSeconds();
const tesr = new TimeLimitedCache();

setTimeout(()=>console.log(tesr.set(1,42,50)),start)
setTimeout(()=>console.log(tesr.set(1,50,100)),start+40)
setTimeout(()=>console.log(tesr.get(1)),start+50)
setTimeout(()=>console.log(tesr.get(1)),start+120)
setTimeout(()=>console.log(tesr.get(1)),start+200)
setTimeout(()=>console.log(tesr.count(1)),start+250)

enter image description here


Solution

  • u can use an object to store timers by key

    this.timers = {}; 
    

    and u don't need to create timer in function (key, value, duration). Remember to clearTimeout of each key.

    this.set = function (key, value, duration) {
        let result = false;
        
        if (key in this.cache) {
            clearTimeout(this.timers[key]);
            result = true;
        }
    
        this.cache[key] = value;
        this.timers[key] = setTimeout(() => delete this.cache[key], duration);
        
        return result;
    }