Milos
Milos

Reputation: 1263

I'm trying to rewrite memoize in javascript (for underscore), can someone explain this?

I know that the purpose of memoize is to cache values so code can be run faster by not having to re-calculate the same answer everytime. My issue stems from returning a function (i think). The google chrome debugger isn't that useful for me here because everytime I try to run this memoize function, it just goes from the argus variable (on line 4 i believe) all the way down to the semi-colon. Furthermore, result always returns an empty object instead of storing a value in result.

I start by defining a function:

function add(a,b){
  return a+b;
}

This is my attempt at the memoize function:

  _.memoize = function(func) {

    var result = {};
    var flag = 0;
    var argus = Array.prototype.slice.call(arguments)
    return function() {
        
        if(result[key] === arguments){
            flag = 1
        }
        else if(flag = 0){
          result[argus] = func.apply(this, argus);
        }
        
      return result[argus];
    };
  };

I'd call memoize by doing _.memoize(add(2,5)) but the result doesn't get stored in the result object.

Am I even close to getting this memoize function working properly? Any guidance you guys can give here would be appreciated.

Upvotes: 0

Views: 1265

Answers (1)

JLRishe
JLRishe

Reputation: 101672

The biggest point you're missing is that _.memoize is called on the function first, and it returns a new function. You are calling it on the result of a function call (which is the number 7 in this case).

In order to get it to work, you need to rearrange a few things.

Also note that it's not wise to try to use an array itself as the index to an object. One approach to get around that would be to convert the arguments array to JSON and use that as the index on the results object:

function add(a, b) {
  console.log('Called add(' + a + ', ' + b + ')');

  return a + b;
}

var _ = {};

_.memoize = function(func) {
  var results = {};
  return function() {
    var args = Array.prototype.slice.call(arguments);
    var key = JSON.stringify(args);

    if (!(key in results)) {
      results[key] = func.apply(this, args);
    }

    return results[key];
  };
};

var madd = _.memoize(add);

console.log(madd(2, 4));
console.log(madd(9, 7));
console.log(madd(2, 4));

Upvotes: 2

Related Questions