QuickSnip LogoA light blue logo with a thunderbolt in bracketsQuickSnip

Once

Verified

Creates 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.json

Code

/** 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