Explorer
JavaScript

Write a function `once(fn)` that ensures `fn` is only called once. Subsequent calls return the result of the first invocation.

Problem Statement

<p>Write a function <code>once(fn)</code> that ensures <code>fn</code> is only called once. Subsequent calls return the result of the first invocation.</p>

Examples

Input: const fn = once((x) => x * 2); fn(5); fn(10);

Output: 10 on both calls

Explanation: Second invocation returns cached initial result.

Complexity

Time Complexity: O(1)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: Use a boolean flag to track if the function has been called. šŸ’” Hint 2: Store the result of the first call and return it for subsequent calls. šŸ’” Hint 3: let called = false, result; return function(...args) { if (!called) { called = true; result = fn(...args); } return result; };

Editorial & Approach

Problem Overview & Intuition

To solve Once Function, we consider the execution characteristics of JavaScript engines. Write a function `once(fn)` that ensures `fn` is only called once. Subsequent calls return the result of the first invocation. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.

Step-by-Step Approach

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (use a boolean flag to track if the function has been called).
  3. Implement Logic: Handle state and transformations efficiently (store the result of the first call and return it for subsequent calls).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function once(fn) {
  let called = false;
  let result;
  return function(...args) {
    if (!called) {
      called = true;
      result = fn.apply(this, args);
    }
    return result;
  };
}

Complexity Analysis

Time Complexity O(1) wrapper invocation overhead
Space Complexity O(1) closure scope retention

Edge Cases & Corner Traps Handled

  • Empty or boundary inputs (empty arrays, strings, zero length).
  • Type checks and unexpected values (e.g. null, undefined, negative numbers).
  • Closure preservation and memory isolation between separate invocations.

Once Function

Medium

Write a function once(fn) that ensures fn is only called once. Subsequent calls return the result of the first invocation.

Example Scenarios
1Example 1
Input: const fn = once((x) => x * 2); fn(5); fn(10);
Output: 10 on both calls
Explanation:

Second invocation returns cached initial result.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
[1,1,1,1]