Implement _.once()

Easy
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Implement _.once()

Approach

Use a closure to track whether the function has been called via a boolean flag. On the first call, execute the function, store the result, and set the flag. On subsequent calls, return the cached result without re-executing.

Complexity Analysis

Time
O(1)
Space
O(1)

Pattern

Once Pattern

Why It Works

The closure captures a mutable boolean and result variable that persist across calls, ensuring the wrapped function body runs exactly once regardless of how many times the wrapper is invoked.

Updated Feb 2026