JS how to cache a variable

后端 未结 5 1257
一生所求
一生所求 2020-12-04 14:37

What I want to do is to be able to create a variable, give it a value, close and reopen the window, and be able to retrieve the value I set in the last session. What is the

5条回答
  •  一个人的身影
    2020-12-04 14:48

    I have written a generic caching func() which will cache any variable easily and very readable format. Caching function:

    function calculateSomethingMaybe(args){
      return args;
    }
    
    function caching(fn){
      const cache = {};
      return function(){
        const string = arguments[0];
        if(!cache[string]){
          const result = fn.apply(this, arguments);
          cache[string] = result;
          return result;
        }
        return cache[string];
      }
    }
    
    const letsCache = caching(calculateSomethingMaybe);
    
    console.log(letsCache('a book'), letsCache('a pen'), letsCache('a book'));
    

提交回复
热议问题