Allow One Function Call - Problem
Function Call Limiter: Create a function wrapper that ensures another function can only be called once.

Given a function fn, return a new function that behaves exactly like the original function on its first call, but returns undefined for all subsequent calls.

Key Requirements:
• First call: Return the same result as fn
• All subsequent calls: Return undefined
• The original function should never be executed more than once

This pattern is commonly used in JavaScript libraries to prevent accidental multiple initializations or expensive operations from running repeatedly.

Input & Output

basic_function.js — JavaScript
$ Input: fn = () => 5 calls = [[], [], []]
Output: [5, undefined, undefined]
💡 Note: The first call executes the function and returns 5. All subsequent calls return undefined because the function has already been executed once.
function_with_arguments.js — JavaScript
$ Input: fn = (a, b) => a + b calls = [[2, 3], [1, 4], [10, 20]]
Output: [5, undefined, undefined]
💡 Note: Only the first call with arguments (2, 3) executes, returning 5. Later calls with different arguments still return undefined.
side_effects.js — JavaScript
$ Input: fn = () => { console.log('executed'); return 42; } calls = [[], [], []]
Output: [42, undefined, undefined] (console shows 'executed' only once)
💡 Note: The function with side effects (console.log) only executes once, proving that the original function is never called more than once.

Constraints

  • 1 ≤ calls.length ≤ 10
  • 0 ≤ calls[i].length ≤ 100
  • 2 ≤ JSON.stringify(calls).length ≤ 1000

Visualization

Tap to expand
Function Call Limiting Mechanismonce(fn) → Creates wrapper with closure containing 'called' flagClosure preserves state between multiple invocationsFirst Call: called = falseExecute fn(args)1. Set called = true2. Return fn resultLater Calls: called = trueSkip execution1. Check called = true2. Return undefinedResult: fn output(e.g., "Hello World")Result: undefined(function not executed)🔑 Key: Boolean flag prevents re-execution
Understanding the Visualization
1
Setup Closure
Create wrapper function with private called flag
2
First Call
Flag is false, execute function, set flag to true, return result
3
Guard Check
Flag is true, skip execution, return undefined immediately
Key Takeaway
🎯 Key Insight: A single boolean flag in a closure is all we need to ensure a function only executes once, providing O(1) performance with minimal memory usage.
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28
52.3K Views
Medium Frequency
~12 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen