Files
start-os/sdk/base/lib/util/once.ts
Matt Hill d4e019c87b add comments to everything potentially consumer facing (#3127)
* add comments to everything potentially consumer facing

* rework smtp

---------

Co-authored-by: Aiden McClelland <3732071+dr-bonez@users.noreply.github.com>
2026-02-24 14:29:09 -07:00

23 lines
571 B
TypeScript

/**
* Wraps a function so it is only executed once. Subsequent calls return the cached result.
*
* @param fn - The function to execute at most once
* @returns A wrapper that lazily evaluates `fn` on first call and caches the result
*
* @example
* ```ts
* const getConfig = once(() => loadExpensiveConfig())
* getConfig() // loads config
* getConfig() // returns cached result
* ```
*/
export function once<B>(fn: () => B): () => B {
let result: [B] | [] = []
return () => {
if (!result.length) {
result = [fn()]
}
return result[0]
}
}