简体   繁体   中英

creating _.memoize function that takes in a function as a parameter

I just started learning about memoization today and i am having a hard time wrapping my head around it. I am trying to create a memoize function that stores the result of the parameter function that has been called already and return its value instead of calling it again This is my code:

_.memoize = function(func) {
    var stored = {};

    if (stored.hasOwnProperty('calculated')) {
      return stored['calculated'];
    }

    stored['calculated'] = func;

    return func;
  };

The test cases are:

var spy = sinon.spy(function() { return 'Dummy output'; });
var memoSpy = _.memoize(spy);
memoSpy(10);
expect(spy).to.have.been.calledOnce;
memoSpy(10);
expect(spy).to.have.been.calledOnce;

And:


var spy = sinon.spy(function() { return 'Dummy output'; });
var memoSpy = _.memoize(spy);
memoSpy([1, 2, 3]);
expect(spy).to.have.been.calledOnce;
memoSpy([1, 2, 3]);
expect(spy).to.have.been.calledOnce;

I thought my stored object stores the result of func?

The error i am getting is basically saying that 'spy' should have been called once yet its getting called twice.

The problem is, you are returning the original func. you have to do some 2nd order stuff like

var memoize = function(func) {
  var stored = {};

  return (function() {      
    if (!stored.hasOwnProperty('calculated')) {
      stored['calculated'] = func();
    }

    return stored['calculated'];
  });
};

// To test
var x = function() { console.log('function called'); return 42; }

y = memoize(x)

y()
// => function called
// 42

y()
// 42

Where you basically return a modified/extended function that wraps the original func and adds the memoizing behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM