This is an interview question/answer I found online (link).
Original Question: How could you cache execution of any function?
Example Answer:
function cacheFn(fn) {
var cache = {};
return function wrapper(arg){
if (cache[arg]){
console.log('used cache!!');
return cache[arg];
}
else{
cache[arg] = fn(arg);
return cache[arg];
}
}
}
My initial idea was that, cache
will be removed after cacheFn
is first called so no caching will be done. But when I tested it as below...
function func(n) {
return n+1;
}
const cachef1 = cacheFn(func);
console.log(cachef1(1));
console.log(cachef1(1)); // 'used cache!!'
I'm not understanding how var cache = {};
survived after the first cachef1(1);
call. It's as if when assigning cacheFn(func1)
to cachef1
, the whole block inside cacheFn
were saved. I also found this does not do caching:
cacheFn(func)(1);
cacheFn(func)(1); // no caching when there was no assignment
What concept am I missing or are confused about here?