easycodingjavascript~8 min
Implement once(fn)
Objective: Wrap functions with closures while preserving arguments and `this`.
Write a wrapper that lets a function run only on the first call. Later calls return the first result.
- The wrapped function runs at most once.
- Every call returns the first call's result.
- The first call receives the caller's arguments and `this`.
const init = once(() => ++n); init(); init();
→ n === 1
JavaScript
⌘/Ctrl + Enter to run tests · Esc then Tab leaves the editor
Output
> Nothing has run yet.
Interview follow-up questions
- What should happen if fn throws on the first call?
- How would you extend this to memoize by arguments?
- How is this different from lodash `before`?