简体   繁体   English

我正在尝试用javascript(下划线)重写备忘录,有人可以解释吗?

[英]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. 谷歌浏览器调试器对我来说不是那么有用,因为每次我尝试运行此备忘录功能时,它只是从argus变量(我相信第4行)一直到分号。 Furthermore, result always returns an empty object instead of storing a value in result. 此外,result总是返回一个空对象,而不是在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. 我会通过做_.memoize(add(2,5))来调用备忘录,但结果不会存储在结果对象中。

Am I even close to getting this memoize function working properly? 我什至要使此记忆功能正常工作吗? Any guidance you guys can give here would be appreciated. 大家可以在这里提供任何指导。

The biggest point you're missing is that _.memoize is called on the function first, and it returns a new function. 您缺少的最大点是, _.memoize函数上调用_.memoize ,然后它返回一个新函数。 You are calling it on the result of a function call (which is the number 7 in this case). 您正在根据函数调用的结果 (在这种情况下为7 )调用它。

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: 解决该问题的一种方法是将arguments数组转换为JSON并将其用作results对象上的索引:

 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)); 

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

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