DEV Community

Discussion on: Memoization in JS

Collapse
 
superyarik profile image
superyarik • Edited

i've fix your last example with time

const memoizeTimeout = (fn,time) => {

  let cache = {};

  return (...args) => {

      //Create hash.
      const n = btoa(args);

      //Erase cache.
      setTimeout(()=>{
        if (n in cache){    
          delete cache[n];
        }
      },time);

      //Find in cache or store new values.      
      if (n in cache){        
        return cache[n];
      } else {    
        let result = fn(...args);        
        cache[n] = result;

        return result;
      }

  }

}
Enter fullscreen mode Exit fullscreen mode

no need to clearInterval - couse it clean setInterval after first run and not work correct for many launches with different params