Allow One Function Call - Problem

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.

Requirements:

  • 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

Input & Output

Example 1 — Basic Addition Function
$ Input: fn = (a,b) => a + b, calls = [[1,2], [3,4]]
Output: [3, undefined]
💡 Note: First call: fn(1,2) executes and returns 1+2=3. Second call: fn(3,4) doesn't execute, returns undefined.
Example 2 — Single Call Only
$ Input: fn = (a,b,c) => a + b + c, calls = [[2,3,6]]
Output: [11]
💡 Note: Only one call made: fn(2,3,6) = 2+3+6 = 11. Function executes normally on first call.
Example 3 — Multiple Blocked Calls
$ Input: fn = (a,b) => a * b, calls = [[5,7], [2,4], [1,3]]
Output: [35, undefined, undefined]
💡 Note: First call: fn(5,7) = 5*7 = 35. Second and third calls return undefined as function already executed once.

Constraints

  • fn is a valid JavaScript function
  • fn can be called with 0 or more arguments
  • calls.length ≥ 1
  • 0 ≤ calls[i].length ≤ 10

Visualization

Tap to expand
Allow One Function Call INPUT fn = (a,b) => a + b Original Function Calls Array: [1, 2] Call #1 [3, 4] Call #2 Initial State: called = false Memoization Pattern Store state in closure Track if fn was called Return cached behavior ALGORITHM STEPS 1 Create Closure Initialize called = false 2 Return Wrapper Fn New function with guard 3 Check Flag If called: return undefined 4 Execute Once Set called=true, run fn function once (fn) { let called = false return (...args) => { if (called) return called = true return fn (...args) } } FINAL RESULT Call #1: fn(1, 2) called = false --> true Returns: 3 Call #2: fn(3, 4) called = true (blocked!) Returns: undefined Output Array: [3, undefined] OK - Function limited to single execution Key Insight: The Memoization Pattern uses closures to maintain state across function calls. By storing a boolean flag in the closure scope, the wrapper function can track whether the original function has been called and prevent subsequent executions. This pattern is useful for initialization functions and event handlers. TutorialsPoint - Allow One Function Call | Memoization Pattern
Asked in
Meta 15 Google 12
12.5K Views
Medium Frequency
~8 min Avg. Time
425 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