Run a function only once
Wrap a function so it executes on the first call and returns the same result afterwards.
- JavaScript
- GreenSnippets
- MIT
- Executed with Node.js 22
function once(fn) {
let called = false;
let result;
return function (...args) {
if (!called) {
called = true;
result = fn.apply(this, args);
}
return result;
};
}Example / expected output
const init = once(() => loadConfig());
init(); init(); // loadConfig runs onceHow it works
Useful for lazy initialization, one-time setup and idempotent handlers. The result (including a returned promise) is cached, so concurrent callers share one in-flight operation.
Related snippets
- JavaScript Tested
Memoize a function
Cache results by argument so expensive pure functions only run once per distinct input.
- TypeScript Tested
Debounce with preserved argument types
A debounce function whose returned function keeps the parameter types and exposes cancel() and flush().
- JavaScript Tested
Curry a function
Turn a multi-argument function into one that can be called a few arguments at a time.
- JavaScript Tested
Compose and pipe functions
Chain single-argument functions left-to-right with pipe, or right-to-left with compose.

