javascript - 在 JavaScript 中实现自动内存(返回闭包函数)

标签 javascript node.js memoization

我读过

http://www.sitepoint.com/implementing-memoization-in-javascript/

自动内存

In all of the previous examples, the functions were explicitly modified to add memoization. It is also possible to implement a memoization infrastructure without modifying the functions at all. This is useful because it allows the function logic to be implemented separately from the memoization logic. This is done by creating a utility function which takes a function as input and applies memoization to it. The following memoize() function takes a function, “func”, as input. memoize() returns a new function which wraps a caching mechanism around “func”. Note that this function does not handle object arguments. In order to handle objects, a loop is required which would inspect each argument individually and stringify as needed.

function memoize(func) {
  var memo = {};
  var slice = Array.prototype.slice;

  return function() {
    var args = slice.call(arguments);

    if (args in memo)
      return memo[args];
    else
      return (memo[args] = func.apply(this, args));

  }
}

用这个,我做到了

var fib = function(n)
{
  if (n <= 1)
  {
    return 1; // as the Fib definition in Math
  }
  else
  {
    return fib(n - 2) + fib(n - 1); // as the Fib definition in Math
  }
};

log(memoize(fib)(43));
log(fib(43));

但是,我确认没有效果。

出于同样的目的,我还尝试了 npm 库,

https://github.com/medikoo/memoize

var memoize = require('memoizee');

log(memoize(fib)(43));
log(fib(43));

结果是一样的。

我错过了什么,如何修复并使其发挥作用?

谢谢!

编辑

require('memoizee');

var fib = function(n)
{
  if (n <= 1)
  {
    return 1; // as the Fib definition in Math
  }
  else
  {
    return fib(n - 2) + fib(n - 1); // as the Fib definition in Math
  }
};

var generator = function(f)
{
  return memoize(f);
};

var _fib = generator(fib);
console.log(_fib(40)); //no effect

最佳答案

memoize 调用不会改变 fib 函数,而是返回其新的、已内存的对应函数。在您的代码中,您仅调用该函数一次,下次调用原始 fib 函数。您需要创建一个内存的“包装器”,并调用它多次次:

var mFib = memoize(fib);
log(mFib(43));
log(mFib(43));

您还可以覆盖原始的 fib = memoize(fib);,这将带来额外的好处,即递归调用(有趣的调用)也将被内存。

关于javascript - 在 JavaScript 中实现自动内存(返回闭包函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24488862/

相关文章:

javascript - 将 JQuery ajax 调用转换为 vanilla Javascript - 无法 POST/public/error

node.js - 如何检查文档是否包含 Cloud Firestore 中的属性?

lisp - 我如何在 Lisp 中内存一个递归函数?

python - 记忆化使用/缓存存储

javascript - div 由 iframe 覆盖

c# - div 从 asp.net 中的代码后面添加重定向和背景图像

javascript - 如何动态地将表单字段转换为多维js对象?

javascript - 困难的 css 样式 : button alignment AND changing fieldnames AND dynamic text length

mysql - nodejs上是否有支持存储过程的mysql驱动程序?

julia - 在 Julia 的函数中本地化内存