Implement Once
EasyUtility Functions10 min4 tests
Implement a once function that ensures the provided function is only called once. Subsequent calls should return the result of the first invocation.
Requirements
- The wrapped function should execute only on the first call
- Return the cached result on all subsequent calls
- Preserve
thiscontext and arguments on the first call
Example
const initialize = once(() => { console.log('Init!'); return 42; });
initialize(); // logs "Init!", returns 42
initialize(); // returns 42 (no log)Hints (3)
- Use a boolean flag to track if the function has been called.
- Cache the result of the first call in a closure variable.
- Return the cached result on subsequent calls.
Topics
- Utility Functions
Asked at
Google · Amazon · Apple
