HTML and CSS Reference
In-Depth Information
Listing 6.26 Memoizing the Fibonacci sequence in a closure
var fibonacci = (function () {
var cache = {};
function fibonacci(x) {
if (x < 2) {
return 1;
}
if (!cache[x]) {
cache[x] = fibonacci(x - 1) + fibonacci(x - 2);
}
return cache[x];
}
return fibonacci;
}());
This alternative version of fibonacci runs many orders of magnitude faster
than the original one, and by extension is capable of calculating more numbers in
the sequence. However, mixing computation with caching logic is a bit ugly. Again,
we will add a function to Function.prototype to help separate concerns.
The memoize method in Listing 6.27 is capable of wrapping a method, adding
memoization without cluttering the calculation logic.
Listing 6.27 A general purpose memoize method
if (!Function.prototype.memoize) {
Function.prototype.memoize = function () {
var cache = {};
var func = this;
return function (x) {
if (!(x in cache)) {
cache[x] = func.call(this, x);
}
return cache[x];
};
};
}
 
Search WWH ::




Custom Search