Last Updated: February 25, 2016
· chinchang

Function with cached values

Here is a small code snippet demonstrating how to cache values inside Javascript functions itself. Lets say you have a function to calculate factorial using recursion:

function factorial (n) {
 if(n == 1) return 1;
 return n * factorial(n-1);

Now every time you need factorial of, say 9, it goes into recursion. To remove this duplicate computation, lets cache values inside the function itself. As we know, functions in Javascript are objects, so lets make a cache property of the function which stores the calculated values in it:

function factorial (n) {
 if(arguments.callee.cache[n]) return arguments.callee.cache[n];
 if(n == 1) return 1;
 var result = arguments.callee.cache[n] = n * factorial(n-1);
 return result;
factorial.cache = [];

And you get a self cached factorial function!

More read: http://ejohn.org/apps/learn/#19

Say Thanks