JavaScript Closure Memorization
js閉包記憶化程式設計學習
利用記憶化使遞迴次數大大減少。
以Fibonacci數列為例:
var fibonacci = function(){
var memo = [0, 1];
var fib = function(i){
var result = memo[i];
if(typeof result !== 'number'){
result = fib[i-1]+fib[i-2];
memo[i] = result;
}
return result;
}
return fib;
}();
for(var i = 0; i < 10; ++i){
console.log(fibonacci(i));
}
進一步封裝:
var memoizer = function(memo, fundamental){
var shell = funciton(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);
})
//階乘
var factorial = memoizer([1,1], function(shell, n){
return shell(n-1)*n;
})
相關文章
- Javascript ClosureJavaScript
- Javascript閉包(Closure)JavaScript
- 學習Javascript閉包(Closure)JavaScript
- javascript中的閉包closure詳解JavaScript
- 深入淺出JavaScript之閉包(Closure)JavaScript
- Js closure and bindJS
- JS閉包ClosureJS
- PHP 閉包(Closure)PHP
- JavaScript變數作用域(Variable Scope)和閉包(closure)的基礎知識JavaScript變數
- JS中的 閉包(Closure)JS
- JS-閉包(closure)的理解JS
- 閉包捕捉(closure capture)淺析APT
- Lua的function、closure和upvalue(轉)Function
- [Memory leak] 3. Garbage collection in Closure
- Dart 進階 | 深入理解 Function & ClosureDartFunction
- python closure閉包 lambda表示式Python
- 使用func和closure加工資料(一)
- Robust Loop Closure by Textual Cues in Challenging EnvironmentsOOP
- PHP 的Closure的bind 詳細介紹PHP
- Closure的應用和替代方案比較
- Java中的閉包(Closure)和回撥Java
- rust-quiz:021-closure-or-logical-or.rsRustUI
- [正兒八經PHP]PHP閉包(Closure)初探PHP
- 使用 deploy 部署專案時報 Serialization of 'Closure' is not allowed 錯誤
- php 使用Callable Closure強制指定回撥型別PHP型別
- 10.2解決了10.1以下的Transitive Closure變化
- PHP編譯器BPC 6.0釋出,支援namespace,支援closure,成功編譯 workermanPHP編譯namespace
- PHP 中`Closure`和`Callable`的區別以及在 Redis 訂閱方法中的使用PHPRedis
- 論文閱讀 Dynamic Network Embedding by Modeling Triadic Closure Process
- JavaScript高階:JavaScript物件導向,JavaScript內建物件,JavaScript BOM,JavaScript封裝JavaScript物件封裝
- javaScript系列[06]-javaScript和thisJavaScript
- 【JavaScript學習】JavaScript物件建立JavaScript物件
- 【轉】eval()函式(javascript) - [javaScript]函式JavaScript
- [Javascript] How javascript read the property?JavaScript
- JavaScript -"this"JavaScript
- javascript ??JavaScript
- This in JavaScriptJavaScript
- “This” is For JavaScriptJavaScript