We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Allow One Function Call

Difficulty: Easy


Problem Description

Given a function fn, return a new function that is identical to the original function except that it ensures fn is called at most once. The first time the returned function is called, it should return the same result as fn. Every subsequent time it is called, it should return undefined.


Key Insights

  • The returned function must track whether it has been called before.
  • It should cache the result of the first call to return it on the first execution.
  • Any further calls should simply return undefined, ignoring the provided arguments.

Space and Time Complexity

Time Complexity: O(1) for each function call after the first. Space Complexity: O(1), as we only store the result of the first function call.


Solution

To solve this problem, we can create a closure that captures the state of the function execution. The closure will keep track of whether the function has been called and store the result of the first call. When the returned function is invoked, it checks if it has been called before; if not, it calls the original function and stores the result. For any subsequent calls, it returns undefined, ensuring that the original function is only executed once.


Code Solutions

function once(fn) {
    let called = false;
    let result;
    
    return function(...args) {
        if (!called) {
            called = true;
            result = fn(...args);
            return result;
        }
        return undefined;
    };
}
← Back to All Questions