Memoize a currified function

前端 未结 3 1693
别那么骄傲
别那么骄傲 2021-01-31 15:37
const f = (arg1) => (arg2) => { /* returns something */ }

Is it possible to memoize f with regard to the 2 arguments, namely:

f(1         


        
3条回答
  •  春和景丽
    2021-01-31 16:17

    Interesting question — you could have independent caches for each function. The cache on the outside function will hold functions. Each inside function could get its own independent cache. So calling f(10)(1) followed by f(10)(2) would result in calling a cached version of the inside function. Calling f(10)(1) again would hit both caches:

    function getCachedF() {
      // outer cache holds functions keyed to argument
      let outer_memo = {}  
                    
      const f = (arg1) => {
        if (!outer_memo.hasOwnProperty(arg1)) {
          // Create inner function on outer cache
          // each inner function needs its own cache
          // because it will return different values
          // given different outer function calls
          let inner_memo = {}                  
          console.log("outer cache miss")
          
          outer_memo[arg1] = (arg2) => {
            // just a normal memoized function
            // cache is simple key:value pair
            if (!inner_memo.hasOwnProperty(arg2)) {
              console.log("inner cache miss")
              inner_memo[arg2] = arg1 + arg2
            }
            return inner_memo[arg2]
          }
        }
        return outer_memo[arg1]
      }
      return f
    }
    
    let f = getCachedF()
    // both caches miss
    console.log("3+5", f(3)(5))
    
    // cached result
    console.log("3+5", f(3)(5))
    
    // only inside cache hit
    console.log("3+8", f(3)(8))
    
    // inside cache only hits if both args are the same
    console.log("10+8", f(10)(8))

    Another alternative would be to have single cache with keys that are a combination of both arguments, but then the inner function would always have to be called.

提交回复
热议问题