Home > Mobile >  decorators closure JS need to understand
decorators closure JS need to understand

Time:08-27

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:

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

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

CodePudding user response:

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) {
      called = true;
      result = callback(...args);
    }
    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);

  • Related