Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

239
Views
Decorator function flow in javascript

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));

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!