Allow One Function Call - Problem
Function Call Limiter: Create a function wrapper that ensures another function can only be called once.
Given a function
Key Requirements:
• First call: Return the same result as
• All subsequent calls: Return
• 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.
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
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code