DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on • Updated on

Day 7: Once

Question:

Write a function called once that takes a function as an argument and returns a new function. The new function should only call the original function once and return its result for subsequent calls.


function once(fn) {
 // Todo add your code
}

function expensiveOperation() {
  // Time-consuming calculation
  console.log("Executing expensive operation...");
  return "Result";
}

const executeOnce = once(expensiveOperation);
console.log(executeOnce()); // Result
console.log(executeOnce()); // Result

Enter fullscreen mode Exit fullscreen mode

🤫 Check the comment below to see answer.

Top comments (1)

Collapse
 
dhrn profile image
Dharan Ganesan
function once(fn) {
  let hasBeenCalled = false;
  let result;

  return function (...args) {
    if (!hasBeenCalled) {
      result = fn.apply(this, args);
      hasBeenCalled = true;
    }

    return result;
  };
}
Enter fullscreen mode Exit fullscreen mode