Once (Function Wrapper)

easy
By FrontendAtlas Editorial · Updated Nov 12, 2026
Implement once(fn) that returns a wrapper which executes fn only on the first call. Cache and return the result on subsequent calls without re-invoking fn. This tests closures, memoization, and side-effect control. Concepts: higher-order, functions, closure.

Arguments

  • fn: Function — The function to call once.

Returns

Function — A wrapped function that only calls fn once.

Solution idea

Wrap a function with a closure that tracks whether it has been called and stores its return value. The first call executes the original function; every later call returns the cached result. This pattern is common for one-time initialization and idempotent setup. Key concepts: higher-order, functions, closure.

Examples
const addOnce = once((a, b) => a + b);
addOnce(1, 2); // 3
addOnce(5, 6); // still 3

const obj = { x: 2, get: once(function (n) { return this.x + n; }) };
obj.get(3); // 5