Java Reference
In-Depth Information
argument"
<< "Squares a number that is provided as an argument"
A useful feature of this is that it provides result caching, or memoization .
If a function takes some time to compute a return value, we can save the result in a cache
property. Then if the same argument is used again later, we can return the value from the
cache, rather than having to compute the result again. For example, say that squaring a
number was an expensive computational operation that took a long time. We could rewrite
the square() function so that it saved each result in a cache object that is a property of
the function:
function square(x){
square.cache = square.cache || {}; // initialize the
cache as an
empty object if it doesn't already exist
if (!square.cache[x]) { // check to see if this value
has already
been saved in the cache
square.cache[x] = x*x; // if not then calculate the
value and
save it in the cache
}
return square.cache[x]
}
If we try calling the function a few times, we can see that the cache object stores the res-
ults:
square(3);
<< 9
square(-11);
<< 121
square.cache;
<< {"3": 9, "-11": 121}
Search WWH ::




Custom Search