Magicsheet logo

Allow One Function Call

Easy
12.5%
Updated 8/1/2025

Asked by 4 Companies

Topics

Allow One Function Call

What is this problem about?

The "Allow One Function Call interview question" is a JavaScript/TypeScript closure problem. You are asked to write a higher-order function that takes another function as an argument and returns a new version of that function. This new version should only be allowed to run once. On the first call, it should return the actual result; on any subsequent calls, it should return undefined, regardless of the arguments passed.

Why is this asked in interviews?

Companies like Yandex and Microsoft use the "Allow One Function Call coding problem" to test a candidate's understanding of Closures and Higher-Order Functions. It evaluates whether you know how to maintain state (a boolean flag) inside a function's scope that persists across multiple invocations. This is a common pattern for initialization logic or preventing duplicate API calls.

Algorithmic pattern used

This problem uses the Closure and Wrapper pattern.

  1. State encapsulation: Define a variable (like hasBeenCalled = false) inside the outer function.
  2. Return a function: The outer function returns a new function that has access to hasBeenCalled.
  3. Logic: When the returned function is executed:
    • If hasBeenCalled is false, set it to true and call the original function using .apply() or spread syntax.
    • If hasBeenCalled is true, return undefined.

Example explanation

Original function: add(a, b) => a + b. Wrapped function: onceAdd = once(add).

  1. onceAdd(2, 3) -> hasBeenCalled is false. Set it to true. Return 5.
  2. onceAdd(4, 5) -> hasBeenCalled is true. Return undefined.
  3. onceAdd(1, 1) -> hasBeenCalled is true. Return undefined.

Common mistakes candidates make

  • Not passing arguments: Forgetting to forward the arguments (a, b, c...) from the wrapper to the original function.
  • Global variables: Using a global flag instead of a local variable within the closure, which would prevent other "once" functions from working independently.
  • Context binding: Forgetting to handle the this context if the function is meant to be used as a method (though less common in simple versions).

Interview preparation tip

Master closures! They are a fundamental part of modern JavaScript. Practice creating "decorators" or "wrappers" that modify the behavior of functions (like throttle, debounce, or memoize).

Similar Questions