How to create a memoize function

I am stumped about this memoize issue. I need to create a function that will check if a value has already been calculated for a given argument, return a previous result, or start a calculation and return that value.

I've spent hours on this and so far I'm new to JS. I cannot figure out how to do this. I cannot use any built-in functionality and would really like to understand what I need to do.

Here's what I have so far, which is so wrong that it looks like pseudocode at the moment. I've searched for existing questions about the memoir, but I can't make any decision yet. Any help is greatly appreciated.

  myMemoizeFunc = function(passedFunc) {
  var firstRun = passedFunc;
  function check(passedFunc){
    if(firstRun === undefined){
        return passedFunc;
    }else{return firstRun;}
  }
  };

      

Sorry, I should have been clearer. Here are my special requirements: myMemoizeFunc should return a function that checks if a computation has already been calculated for the given argument and returns val if possible. The missedFunc is a function that contains the result of the calculation. I realize this may seem like a duplicate, but I note that it is not, as I am having serious difficulties understanding what I should be doing here and need more help than other posts. This is what my thought process brings me, but again, I leave.

myMemoizeFunc = function(passedFunc) {
var allValues = [];
return function(){
    for(var i = 0; i < myValues.length; i++){
        if(myValues[i] === passedFunc){
            return i;
        }
        else{
            myValues.push(passedFunc);
            return passedFunc;
        }
    }
  }
};

      

I shouldn't be returning me or passFunc here, but what else could I do in the if / else when checking the value? I have been looking at this problem for a long time, I am starting to implement code that is funny and needs some fresh advice.

+3


source to share


2 answers


I think the main trick for this is to create an object that stores the arguments that were passed earlier as keys, with the result of the function as values.

For memoizing functions of one argument, I would implement it like this:

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

      



Then you can use this to memoize any function that takes a single argument, like a recursive function to calculate factorials:

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

      

+7


source


Several memoization libraries are available. Effective substitution is not as straightforward as it sounds. I suggest using a library. Two of the fastest:

https://github.com/anywhichway/iMemoized



https://github.com/planttheidea/moize

0


source







All Articles