简体   繁体   English

创建 _.memoize function 将 function 作为参数

[英]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 存储已调用的参数 function 的结果并返回其值而不是再次调用它这是我的代码:

_.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?我以为我存储的 object 存储了 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.您基本上返回一个修改/扩展的 function 包装原始func并添加记忆行为的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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