记住一个currified函数

ama*_*iny 23 javascript caching memoization currying

const f = (arg1) => (arg2) => { /* returns something */ }
Run Code Online (Sandbox Code Playgroud)

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

f(1)(2);
f(1)(3); // Cache not hit
f(4)(2); // Cache not hit
f(1)(2); // Cache hit
Run Code Online (Sandbox Code Playgroud)

Nin*_*olz 31

您可以使用Mapas缓存并为所有后续参数获取嵌套映射.

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

它的工作原理是通过一个curried函数和一个可选项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
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)

  • 你能不能再详细一点你的答案(解释)很难理解所有这些功能是如何工作的;) (2认同)
  • @cars10m,在地图中,键可以是任何类型,因为对象只知道字符串和符号。 (2认同)