Problem Statement: How can we cache results in javascript?
The problem: Let us say we have a prolonged running function that needs to be called again and again
This becomes a problem as we want the function to run faster if possible like when the result achieved would be the same as any of the previous results.
This could also be when the function has been called with the same parameters as before.
So in a sense, we want to cache this function’s result and be able to use the cached result when necessary.
To solve this, what we need are as follows:
1. Closures
2. Functions that return other functions.
We can thus create a function that memoizes this slow running function and caches the results.
Let us take an example here:
function slowAf(n) {
let x =2;
let y=3;
let z=0;
for(var i=0;i<n;i++){
for(var j=0;j<n;j++){
z=x*y;
}
}
return z+n;
}
The above function takes an argument and continues to run for a long time before giving a result.
When we execute it again and again, it will always run for a long time before we can expect an output. This becomes redundant in a case when we pass the same arguments to it and call it again.
Now let us change the approach and create a function that can cache its result.
function memoizer(fun) {
var cache = [];
return function(n) {
var idx = n.toString();
if(cache[idx]==undefined){
cache[idx] = fun(n)
}
return cache[idx]
}
}
Now let us breakdown our memoizer function.
- First, we declare a cache array that will hold the cached results of our original function.
- We also pass the actual function to compute as a parameter to this memoizer function.
- Second, we return a closure or simply an inner function, which shall allow us to compute the function we pass.
- We need to ensure that the closure function we create is very similar to the original function we are trying to compute. In our case, we need to create a function with one parameter and a return value.
- Third, we now create an index using the parameter supplied to the function by converting it to a string or a json object.
- Fourth, we check our cache array with the index we created to see if any result is already available for this index. If it is undefined, we proceed to call the function we earlier passed to our memoizer with the necessary params.
- Finally we return the stored result of this index from our cache.
This finally creates our way to cache values. But there is one more step before we are ready to start calling this function.
var cachedFun = memoizer(slowAf)
Here we simply use our memoizer function to create a cached copy of our original slowaf function. We can now simply call this to enable our function level caching.
console.log(cachedFun(100000)); console.log(cachedFun(100000));
When we run this now, the first time it can take 3-6 seconds, but the next time, the cached value is checked and we immediately get the result.
As we can see above, for the first time, the execution time comes at nearly 6 seconds, but the next time, since the passed param is already cached, we get a result immediately in nearly 9 seconds.
So this is how to implement function level caching can be implemented easily in javascript and can be very helpful wherever we need to call functions with the same or similar parameters, like a Fibonacci series calculator or in a real-world scenario where we are caching something like episodes for a streaming platform.
Discover more in the next blog!!
I keep on coding something cool, visit ankush.tech to see what all I am doing!
If you wish to read about my work, here is a book that I published recently – “CSS Bullets, a comprehensive guide to all the CSS you need!“
Interested in React? Learn react from scratch with my book, “REACT Bullets“.
Thanks for sticking around!
Till next time, keep howling, hustling, and learning!

Leave a Reply