1

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));
MarioG8
  • 3,423
  • 4
  • 6
  • 20
Ali Mustafa
  • 588
  • 1
  • 9
  • 2
    You're passing it into the second option you mentioned. The original slow function is executed when `let result = func(x); ` runs – Nick Parsons Dec 19 '21 at 03:59
  • And is the `func(x)` taken from the lexical environment of `cachingDecorator` function? – Ali Mustafa Dec 19 '21 at 04:01
  • 2
    Yes, that's right, `func` inside of the function returned from `cachingDecorator` refers to the `func` argument passed to `cachingDecorator`, which in your case is the original `slow` function. – Nick Parsons Dec 19 '21 at 04:03

0 Answers0