FrontendInterviews.dev

Loading problem…

85. Once Function

Easy•
Acceptance: 72.00%
•
🔓3/3 Pro unlocks today

Implement a once function that ensures a function is only executed once, regardless of how many times it's called.

Requirements

1. Basic Functionality

  • Accept a function fn
  • Return a new function that wraps fn
  • The wrapped function should execute fn only on the first call
  • Subsequent calls should return the result from the first call (or undefined if first call returned undefined)
  • Preserve the 'this' context and arguments

Example Usage

const initialize = () => {
  console.log('Initialized');
  return 'setup complete';
};

const initializeOnce = once(initialize);

initializeOnce(); // Logs 'Initialized', returns 'setup complete'
initializeOnce(); // Returns 'setup complete' (no log)
initializeOnce(); // Returns 'setup complete' (no log)

Constraints

  • The function should only execute once
  • Subsequent calls should return the cached result
  • Preserve the 'this' context of the original function
  • Pass all arguments correctly to the original function
  • Handle functions that return undefined