How to create a memoize function

后端 未结 3 745
栀梦
栀梦 2020-12-11 05:07

I am stumped with this memoize problem. I need to create a function that will check to see if a value has already been calculated for a given argument, return the previous r

相关标签:
3条回答
  • 2020-12-11 05:56

    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);
    });
    
    0 讨论(0)
  • 2020-12-11 05:56

    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

    0 讨论(0)
  • 2020-12-11 06:00

    See here for a comprehensive(-ish) list of memoization libraries: https://stackoverflow.com/a/61402805/2441655

    0 讨论(0)
提交回复
热议问题