Implementing a Custom _.once() Function in JavaScript



The _.once method from Lodash ensures that a function is only executed once, no matter how many times it is invoked. After the first call, the function returns the result of the initial execution for all subsequent calls.

Let's implement a custom version of _.once in JavaScript.


What is _.once()?

The _.once() function creates a version of a function that can only be called once. Subsequent calls to the function return the result of the first invocation. This can be useful in scenarios where you want to ensure a function runs only a single time, like initializing resources or setting up configurations.

Real Interview Insights

Interviewers might ask you to:

  • Implement a function that mimics the behavior of Lodash’s _.once.
  • Ensure the function returns the same result for all subsequent calls after the first one.

Implementing customOnce Function

Here’s how you can implement a custom _.once function:

function customOnce(func) {
  let result;
  let called = false;
 
  return function(...args) {
    if (!called) {
      result = func.apply(this, args);
      called = true;
    }
    return result;
  };
}
Explanation:
  • result Variable: Stores the result of the first function call.
  • called Flag: A boolean flag that tracks whether the function has been called.
  • Closure: The returned function retains access to the result and called variables through closure, allowing it to control subsequent executions.

Practical Examples

Let's see the customOnce function in action:

function initialize() {
  console.log('Initializing...');
  return 'Initialization Complete';
}
 
const initializeOnce = customOnce(initialize);
 
console.log(initializeOnce()); // Output: 'Initializing...'
                                //          'Initialization Complete'
 
console.log(initializeOnce()); // Output: 'Initialization Complete'

In this example, initialize() is only executed once, even though initializeOnce() is called twice. The second call simply returns the result of the first execution without running the function again.

Handling Edge Cases

  1. No Arguments: Ensure the function works correctly even when no arguments are provided.
  2. Multiple Calls: Verify that the function consistently returns the first result for any number of subsequent calls.

Use Cases for _.once()

  1. Initialization: Ensure initialization logic, like setting up a database connection or event listeners, is only run once.
  2. Resource Management: Prevent multiple resource allocations or configurations in scenarios where they should occur only once.
  3. Performance Optimization: Avoid unnecessary repeated executions of expensive operations.