Memoize
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) returning a function that calls fn at most once.
The first call passes its arguments through and returns the result. Every later call returns undefined and does not invoke fn again.
Input:
JSfile.javascript1const add = once((a, b) => a + b); 2add(1, 2); // 3 3add(3, 4);
Output:
undefined
The second call is ignored entirely.
undefined rather than the cached first result — Lodash’s once caches, and interviewers ask which you built.Goal: Run the original exactly once, whatever the caller does afterwards.
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 ·