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?
You could attach a hash to the function that you want to cache.
This would require that the function is a 1-1 function with no side effects.