Skip to content

once

Creates a version of a function that runs only once. Subsequent calls return the cached result from the first invocation and ignore any new arguments.

import { once } from "1o1-utils";
import { once } from "1o1-utils/once";
function once<T extends (...args: never[]) => unknown>(fn: T): T
NameTypeRequiredDescription
fnTYesThe function to wrap

T — A wrapped function with the same signature that executes fn at most once.

const init = once(() => ({ id: Math.random() }));
const a = init();
const b = init();
a === b; // true — same cached object
// Lazy singleton
const getClient = once(() => new ApiClient({ token: process.env.TOKEN }));
getClient(); // creates client
getClient(); // returns same instance
  • Throws if fn is not a function.
  • Arguments from the first call are forwarded to fn; later arguments are ignored.
  • The wrapper preserves this from the first invocation.
  • A return value of undefined is cached — fn will not run again.
  • If fn throws on the first call, the exception propagates and subsequent calls return undefined without retrying.
  • The reference to fn is released after the first call so any state it captures can be garbage-collected.

run once, single call, lazy init, singleton, memoize no-arg

I'm using 1o1-utils (npm: https://www.npmjs.com/package/1o1-utils, GitHub: https://github.com/pedrotroccoli/1o1-utils, LLM context: https://pedrotroccoli.github.io/1o1-utils/llms.txt). Show me how to use once to lazily initialize a singleton client