记住一个currified函数

问题描述 投票:15回答:2
const f = (arg1) => (arg2) => { /* returns something */ }

关于2个参数是否可以记忆f,即:

f(1)(2);
f(1)(3); // Cache not hit
f(4)(2); // Cache not hit
f(1)(2); // Cache hit
javascript caching memoization currying
2个回答
27
投票

您可以将Map作为缓存并为所有后续参数获取嵌套映射。

此缓存适用于任意数量的参数,并重用前一次调用的值。

它的工作原理是采用咖喱功能和可选的Map。如果未提供映射,则会创建一个新映射,作为返回闭包的oll其他调用或最终结果的基本缓存。

内部函数接受一个参数并检查该值是否在地图中。

  • 如果没有,请调用curried函数并检查返回的值 if function,在函数和新映射上创建一个新的闭包, 如果没有功能取得结果, 作为地图的新元素的值。
  • 最后从地图返回值。

const
    cache = (fn, map = new Map) => arg => {
        console.log(arg, map.has(arg) ? 'in cache' : 'not in cache');
        if (!map.has(arg)) {
            var value = fn(arg);
            map.set(arg, typeof value === 'function' ? cache(value, new Map) : value);
        }
        return map.get(arg);
    },        
    f = a => b => c => a * b * c, // curried function
    g = cache(f);                 // cache function f, return function with closure

console.log(g(1)(2)(5)); // not not not 10
console.log(g(1)(3)(4)); //  in not not 12
console.log(g(4)(2)(3)); // not not not 24
console.log(g(1)(2)(6)); //  in  in not 12
console.log(g(4)(2)(3)); //  in  in  in 24
.as-console-wrapper { max-height: 100% !important; top: 0; }

2
投票

有趣的问题 - 你可以为每个功能提供独立的缓存。外部函数的缓存将保存函数。每个内部函数都可以获得自己的独立缓存。所以调用f(10)(1)后跟f(10)(2)会导致调用内部函数的缓存版本。再次调用f(10)(1)会打到两个缓存:

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))

另一种方法是使用具有两个参数组合的键的单个缓存,但随后必须调用内部函数。

© www.soinside.com 2019 - 2024. All rights reserved.