Memoize a Function
Cache a function by its arguments so the same call never computes twice.
JavaScript · ES6 — Pratik Rai ·
A once wrapper: the first call runs, every call after it does nothing.
Write once(fn), a wrapper that lets fn run a single time.
The first call passes its arguments through and returns the result. Every later call returns undefined and does not invoke fn again.
Input:
JSfile.javascript1let runs = 0; 2const connect = once((host) => { 3 runs += 1; 4 return 'connected to ' + host; 5}); 6 7[connect('alpha'), connect('beta'), runs];
Output:
['connected to alpha', undefined, 1]
Only the first call reaches the original. The second returns undefined without running it, so runs stays at 1.
undefined rather than the cached first result — Lodash’s once caches, and interviewers ask which you built.once is a two-line function that is really a closure question. The state has to live outside the returned function so it survives between calls.
Flip the flag before invoking, so a throwing first call still counts as the call.
JSfile.javascript1function once(fn) { 2 let called = false; 3 return function (...args) { 4 if (called) return undefined; 5 called = true; 6 return fn.apply(this, args); 7 }; 8}
Later calls return undefined rather than the cached first result. That is a deliberate difference from Lodash's once, which caches and returns the same value forever — interviewers ask which one you built and why.
Each wrapper gets its own flag, so wrapping the same function twice gives two independent one-shot functions.
Goal: Run the original exactly once, whatever the caller does afterwards.
undefined, while Lodash's once caches and returns the first result forever. Interviewers ask which you implemented to see whether you noticed there was a decision.Continue learning with these related challenges
Cache a function by its arguments so the same call never computes twice.
JavaScript · ES6 — Pratik Rai ·
Fold an array of functions into one, applied right to left.
JavaScript · ES6 — Pratik Rai ·
Test your JavaScript skills by predicting console output for tricky code snippets. Covers hoisting, closures, this binding, async operations, and event loop quiz questions.
JavaScript · ES6 — Pratik Rai ·
Cache a function by its arguments so the same call never computes twice.
JavaScript · ES6
Pratik Rai ·
Fold an array of functions into one, applied right to left.
JavaScript · ES6
Pratik Rai ·
Test your JavaScript skills by predicting console output for tricky code snippets. Covers hoisting, closures, this binding, async operations, and event loop quiz questions.
JavaScript · ES6
Pratik Rai ·