JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

8.8.4 Memoization

8.8.4 Memoization


In §8.4.1 we defined a factorial function that cached its previously computed results. In functional programming, this kind of caching is called memoization. The code below shows a higher-order function, memoize() that accepts a function as its argument and returns a memoized version of the function:

// Return a memoized version of f. // It only works if arguments to f all have distinct string representations. function memoize(f) {

var cache = {}; // Value cache stored in the closure.

return function() { // Create a string version of the arguments to use as a cache key. var key = arguments.length + Array.prototype.join.call(arguments,","); if (key in cache) return cache[key]; else return cache[key] = f.apply(this, arguments);

}; }

The memoize() function creates a new object to use as the cache and assigns this object to a local variable, so that it is private to (in the closure of) the returned function. The returned function converts its arguments array to a string, and uses that string as a property name for the cache object. If a value exists in the cache, it returns it directly.

Otherwise, it calls the specified function to compute the value for these arguments, caches that value, and returns it. Here is how we might use memoize():

// Return the Greatest Common Divisor of two integers, using the Euclidian // algorithm: http://en.wikipedia.org/wiki/Euclidean_algorithm function gcd(a,b) { // Type checking for a and b has been omitted

var t; // Temporary variable for swapping values if (a < b) t=b, b=a, a=t; // Ensure that a >= b while(b != 0) t=b, b = a%b, a=t; // This is Euclid's algorithm for GCD return a;

}

var gcdmemo = memoize(gcd); gcdmemo(85, 187) // => 17

// Note that when we write a recursive function that we will be memoizing, // we typically want to recurse to the memoized version, not the original. var factorial = memoize(function(n) {

return (n <= 1) ? 1 : n * factorial(n-1); }); factorial(5) // => 120. Also caches values for 4, 3, 2 and 1.

8.8 Functional Programming | 197

欢迎转载,转载请注明来自一手册:http://yishouce.com/book/1/31374.html
友情链接It题库(ittiku.com)| 版权归yishouce.com所有| 友链等可联系 admin#yishouce.com|粤ICP备16001685号-1