DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 41

The task is to implement the once() function, which is used to force a function to be called only once, later calls only returns the result of first call.

The boilerplate code:

function once(func) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

Create a variable to keep track of whether the function has been called or not.

let called = false;
Enter fullscreen mode Exit fullscreen mode

Create a variable to store the result of the first call, so that later calls can recall the same value

let result;
Enter fullscreen mode Exit fullscreen mode

If the function isn't executed, let it run

return function(...args) {
    if (!called) {
      result = func.apply(this, args);
      called = true;
    }
    return result;
  };
Enter fullscreen mode Exit fullscreen mode

.apply(this, args ensures that the function keeps the correct context and accepts as many arguments as possible.

The final code

function once(func) {
  // your code here
  let called = false;
  let result;

  return function(...args) {
    if(!called) {
      result = func.apply(this, args);
      called = true;
    }
    return result;
  }
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)