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
Written by Kushagra Gour
Related protips
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside