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
Section titled “Import”import { once } from "1o1-utils";import { once } from "1o1-utils/once";Signature
Section titled “Signature”function once<T extends (...args: never[]) => unknown>(fn: T): TParameters
Section titled “Parameters”| Name | Type | Required | Description |
|---|---|---|---|
| fn | T | Yes | The function to wrap |
Returns
Section titled “Returns”T — A wrapped function with the same signature that executes fn at most once.
Examples
Section titled “Examples”const init = once(() => ({ id: Math.random() }));
const a = init();const b = init();a === b; // true — same cached object// Lazy singletonconst getClient = once(() => new ApiClient({ token: process.env.TOKEN }));
getClient(); // creates clientgetClient(); // returns same instanceEdge Cases
Section titled “Edge Cases”- Throws if
fnis not a function. - Arguments from the first call are forwarded to
fn; later arguments are ignored. - The wrapper preserves
thisfrom the first invocation. - A return value of
undefinedis cached —fnwill not run again. - If
fnthrows on the first call, the exception propagates and subsequent calls returnundefinedwithout retrying. - The reference to
fnis released after the first call so any state it captures can be garbage-collected.
Also known as
Section titled “Also known as”run once, single call, lazy init, singleton, memoize no-arg
Prompt suggestion
Section titled “Prompt suggestion”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