How to create a memoize function

僤鯓⒐⒋嵵緔 提交于 2019-11-29 10:57:05

I think the main trick for this is to make an object that stores arguments that have been passed in before as keys with the result of the function as the value.

For memoizing functions of a single argument, I would implement it like so:

var myMemoizeFunc = function (passedFunc) {
    var cache = {};
    return function (x) {
        if (x in cache) return cache[x];
        return cache[x] = passedFunc(x);
    };
};

Then you could use this to memoize any function that takes a single argument, say for example, a recursive function for calculating factorials:

var factorial = myMemoizeFunc(function(n) {
    if(n < 2) return 1;
    return n * factorial(n-1);
});

There are a number of memoization libraries available. Doing memoization efficiently is not as straight forward as it seems. I suggest a library be used. Two of the fastest are:

https://github.com/anywhichway/iMemoized

https://github.com/planttheidea/moize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!