@monstermann/fn
Version:
A utility library for TypeScript.
28 lines (27 loc) • 469 B
JavaScript
//#region src/function/once.ts
/**
* `once(fn)`
*
* Creates a function that executes only once and caches the result for subsequent calls.
*
* ```ts
* const expensive = once(() => {
* console.log("Computing...");
* return 42;
* });
*
* expensive(); // logs "Computing..." and returns 42
*/
function once(fn) {
let called = false;
let ret;
return () => {
if (!called) {
ret = fn();
called = true;
}
return ret;
};
}
//#endregion
export { once };