Cache results for functions?

caching, javascript

Solution

You could attach a hash to the function that you want to cache.

var expensive_fn = function(val) {
  var result = arguments.callee.cache[val];
  if(result == null || result == undefined) {
    //do the work and set result=...
    arguments.callee.cache[val]=result;
  }
  return result;
}
expensive_fn.cache = {};

This would require that the function is a 1-1 function with no side effects.

Problem

In Javascript, is there a way to cache results for functions that are: - a). Computationally expensive. - b). Called multiple times. Take for example a recursive factorial function that gets called frequently. Usually I'd create a separate array such as `facotrialResults = [];` and add my results to them when I calculate them, `factorialResults[x] = result;` However, is there a better way to accomplish this caching without the use of adding a new variable to the global namespace?

Original source