Write a function `once(fn)` that ensures `fn` is only called once. Subsequent calls return the result of the first invocation.
Problem Statement
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
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
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (use a boolean flag to track if the function has been called).
- Implement Logic: Handle state and transformations efficiently (store the result of the first call and return it for subsequent calls).
- 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
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.