I am using the word, memoization, because it is cool and it sounds like a buzzword, and author of the javascript ninja also called it so.
so, what is memoization. " Memoization is the process of building a function which is capable of remembering its previously computed answers. "
so let 's see some sample implementation that realize the memoization.
/**************************************
*@Summary
* this is the js file that demonstrate the use of the memoization (memorization), I called it memoization as it is like some buzzword as Ninja is calling it so.
*
* Memorization is a very common technique that you can save some compute values as a cache, and you can shortcut some long operation if a value has already computed
*
* @Todo:
* this file is not created, will come back to it with implementation
***************************************/
/**
* @Summary
* memoized
* @Usage:
* isPrime.memoized(5)...
* isPrime._values[5]
*/
Function.prototype.memoized = function (key) {
this._values = this._values || {}; // this is a common technique to initialize something that if it does not have a default value, assign one
return this._values[key] !== undefined ?
this._values[key] :
this._values[key] = this.apply(this, arguments); // the reason why not to store this a fn and so some manipulation is because 'this' we are just using the same function
};
/**
* @Summary
* memoize
* @Usage:
* var isPrime = (function(num) {
..
}).memoize();
* isPrime(5)
*/
Function.prototype.memoize = function () {
var fn = this;
return function () {
return fn.memoized.apply(fn, arguments);
};
};
/**
* @Summary
* isPrime
* @Comment: this is the function that we test for memoization
*/
function isPrime(num) {
var prime = num != 1;
for (var i = 2; i < num; i++) {
if (num % i == 0) {
prime = false;
break;
}
}
return prime;
}
and the following code that test the memoizaion.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type ="text/javascript" src="memoization.js"></script>
<script type="text/javascript" src="../unit.js"></script>
<script type="text/javascript">
window.onload = function () {
test("memoization test", function () {
var isPrime_moized = isPrime.memoize();
assert(isPrime_moized(5), "Make sure the function works, 5 is prime.");
assert(isPrime._values[5], "Make sure the answer is cached.");
assert(isPrime.memoized(5), "Make sure the function works, 5 is prime.");
assert(isPrime._values[5], "Make sure the answer is cached.");
});
};
</script>
<style type="text/css" >
#results li.pass { color: Green }
#results li.fail { color: Red }
</style>
</head>
<body>
<ul id="results" />
</body>
</html>
It is believed that with the memoization, you can achieve faster process (trade off spaces for time.)
本文介绍了JavaScript中一种称为缓存的技术,通过缓存已计算的结果来避免重复计算,从而提高程序运行效率。文章提供了实现缓存的具体代码示例,并通过单元测试验证了其正确性和有效性。
173

被折叠的 条评论
为什么被折叠?



