I am trying to understand the flow of execution in this code. As you can see in the snippet, there is a function slow and a cachingDecorator function which takes a function as its parameter. Here we are passing function slow
in it. After passing the function slow, the slow
equals
slow = function(x) {
if (cache.has(x)) { // if there's such key in cache
return cache.get(x); // read the result from it
}
let result = func(x); // otherwise call func
cache.set(x, result); // and cache (remember) the result
return result;
};
Now what I don’t understand is that when we call slow(1)
are we passing the 1
to this slow function
function slow(x) {
// there can be a heavy CPU-intensive job here
console.log(`Called with ${x}`);
return x;
}
or in this
slow = function(x) {
if (cache.has(x)) { // if there's such key in cache
return cache.get(x); // read the result from it
}
let result = func(x); // otherwise call func
cache.set(x, result); // and cache (remember) the result
return result;
};
function slow(x) {
// there can be a heavy CPU-intensive job here
console.log(`Called with ${x}`);
return x;
}
function cachingDecorator(func) {
let cache = new Map();
return function(x) {
if (cache.has(x)) { // if there's such key in cache
return cache.get(x); // read the result from it
}
let result = func(x); // otherwise call func
cache.set(x, result); // and cache (remember) the result
return result;
};
}
slow = cachingDecorator(slow);
console.log(slow);
console.log(slow(1));