Created
November 26, 2013 09:59
-
-
Save silianlinyi/7655948 to your computer and use it in GitHub Desktop.
在计算机领域,记忆(memoization)是主要用于加速程序计算的一种优化技术,它使得函数避免重复演算之前已被处理的输入,而返回已缓存的结果。我们可以把这种技术推而广之,编写一个函数来帮助我们构造带记忆功能的函数。memoizer函数取得一个初始的memo数组和formula函数。它返回一个管理memo存储和在需要时调用formula函数的recur函数。我们把这个recur函数和他的参数传递给formula函数:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var memoizer = function(memo, formula) { | |
var recur = function(n) { | |
var result = memo[n]; | |
if(typeof result !== 'number') { | |
result = formula(recur, n); | |
memo[n] = result; | |
} | |
return result; | |
}; | |
return recur; | |
}; | |
var fibonacci = memoizer([0, 1], function(recur, n) { | |
return recur(n - 1) + recur(n - 2); | |
}); | |
var factorial = memoizer([1, 1], function(recur, n) { | |
return n * recur(n - 1); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment