问题描述
我正在努力了解Crockford的记忆功能。虽然我能够了解它是如何工作的,但我不太了解 基本 参数和内部函数 shell 以及他如何提出 基本(shell,n); 和 函数(shell,n){...} 的。我的意思是,如果我自己编写代码,会导致我得出同样的结论吗?
I'm trying to understand Crockford's memoizer function. While I'm able to follow how it works, I don't quite understand the fundamental argument and the inner function shell and how he came up with fundamental(shell, n); and function(shell, n) {...}. I mean, if I were writing the code myself, what would lead me to the same conclusion?
var memoizer = function (memo, fundamental) {
var shell = function (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = fundamental(shell, n);
memo[n] = result;
}
return result;
};
return shell;
};
var fibonacci = memoizer([0, 1], function(shell, n) {
return shell(n - 1) + shell(n - 2);
});
直觉上,我会做类似的事情:
Intuitively, I would do something like:
function memoizer(memo, someFormula) {
var shell = function() {
// check memo
// if not in memo
// run the formula - someFormula();
// store result in memo
// return result;
return shell;
}
}
var fibonacci = memoizer([0, 1], function(n) {
// return fibonacci formula
};
不可否认,它不是递归的,我遗漏了 n 参数。虽然我知道 shell 和 基本 不一样,我对重叠以及它们之间的关系感到困惑。
我尝试了什么:
我使用过调试器,所以我理解它是如何工作的但我仍然不喜欢我不明白代码背后的动机。
Admittedly, it's not recursive and I've left out the n argument. While I know that shell and fundamental are not the same, I'm confused with the overlap and how they relate to each other.
What I have tried:
I've used the debugger so I understand how it works but I still don't understand the motive behind the code.
推荐答案
var memoizer = function(cachedResults, theRealFunction) {
return function (n) {
if (!cachedResults.hasOwnProperty(n)) {
cachedResults[n] = theRealFunction(n);
}
return cachedResults[n];
};
};
var fibonacci = memoizer([0, 1], function(n) {
console.debug("fibonacci", n);
return fibonacci(n - 1) + fibonacci(n - 2);
});
添加了 shell
参数,以便递归memoized函数可以调用memoized版本本身。但由于它已经存在,存储在 fibonacci
变量中,因此无需将其作为参数传递。
The shell
parameter was added so that the recursive memoized function could call the memoized version of itself. But since that's already available, stored in the fibonacci
variable, there's no need to pass it as a parameter.
这篇关于需要帮助理解crockford的memoizer功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!