HTML and CSS Reference
In-Depth Information
This method offers a clean way to memoize functions, as seen in Listing 6.28.
Listing 6.28 Memoizing the fibonacci function
TestCase("FibonacciTest", {
"test calculate high fib value with memoization":
function () {
var fibonacciFast = fibonacci.memoize();
assertEquals(1346269, fibonacciFast(30));
}
});
The memoize method offers a clean solution but unfortunately only deals with
functions that take a single argument. Limiting its use further is the fact that it
blindly coerces all arguments to strings, by nature of property assignment, which
will be discussed in detail in Chapter 7, Objects and Prototypal Inheritance.
To improve the memoizer, we would need to serialize all arguments to use as
keys. One way to do this, which is only slightly more complex than what we already
have, is to simply join the arguments, as Listing 6.29 does.
Listing 6.29 A slightly better memoize method
if (!Function.prototype.memoize) {
Function.prototype.memoize = function () {
var cache = {};
var func = this;
var join = Array.prototype.join;
return function () {
var key = join.call(arguments);
if (!(key in cache)) {
cache[key] = func.apply(this, arguments);
}
return cache[key];
};
};
}
This version will not perform as well as the previous incarnation because it both
calls join and uses apply rather than call , because we no longer can assume
the number of arguments. Also, this version will coerce all arguments to strings
as before, meaning it cannot differentiate between, e.g., "12" and 12 passed as
 
Search WWH ::




Custom Search