Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

decorators closure JS need to understand

I have a function that i can only call once using closure and a decorator – I thought I understood the idea but I can’t seem to solve it:

Here is the initial function:

export function once(callback) {
  return (...args) => {

    function once(fun){
      let called = false;
    
      return () => {
        if(!called){
          const result = fun(...arguments);
          called = true;
          return result;
        }
      }
    }
    // `callback` must be called once!
    // Its return value must be memorized.
    return callback(...args);  // nothing will happen when called more than once
  };
}

I tried on the last line:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

...
return once(callback(...args));
  };
}

Shouldn’t that call the function only once???

>Solution :

You’ve got many unnecessary levels of nested functions. Just put the closure variables in the top level of once(), then return a nested function.

You also need to move result out of the nested function so it can memorize between calls.

function once(callback) {
  let called = false;
  let result;
  return (...args) => {
    if (!called) {
      result = callback(...args);
      called = true;
    }
    return result;
  }
}

const callit = once((a, b) => {
  console.log("callit");
  return a + b;
});
const callit2 = once((a, b) => {
  console.log("callit2");
  return a - b;
});

let result = callit(2, 3);
console.log(result);
result = callit2(6, 4);
console.log(result);
result = callit(5, 6);
console.log(result);
result = callit2(5, 10);
console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading