Once
VerifiedCreates a function that runs only once and returns the first result on later calls.
- function
- once
Install
npx shadcn@latest add https://quicksnip.dev/r/once.jsonCode
/** Returns a function that runs `fn` only on the first call and returns that same result afterwards. */
export function once<A extends unknown[], R>(fn: (...args: A) => R): (...args: A) => R {
let called = false;
let result: R;
return (...args: A) => {
if (!called) {
called = true;
result = fn(...args);
}
return result;
};
}Usage
const init = once(() => connectToDatabase());
init(); // connects
init(); // returns the same connection