wellcrafted
Version:
Delightful TypeScript patterns for elegant, type-safe applications
46 lines (45 loc) • 1.37 kB
JavaScript
//#region src/function.ts
/**
* Run-at-most-once wrapper. Wrap `fn` so the first call invokes it and caches the result;
* every later call is a no-op that returns that same cached result. Arguments passed after
* the first call are ignored.
*
* Canonical use: an idempotent `[Symbol.dispose]` whose teardown is reachable from more than
* one path and must not run twice. `once` makes that guarantee declarative instead of a
* hand-rolled `let disposed` flag.
*
* This is for the pure "this function body runs at most once" case. A boolean that is ALSO
* read by other methods to short-circuit a dead object is a liveness flag, not a once-guard;
* keep that boolean, `once` does not replace it.
*
* @example
* ```ts
* import { once } from "wellcrafted/function";
*
* const init = once(() => expensiveSetup());
* init(); // runs expensiveSetup()
* init(); // returns the cached result, does not run again
* ```
*
* @example Idempotent disposal
* ```ts
* import { once } from "wellcrafted/function";
*
* const dispose = once(() => closeConnection());
* // safe to call from multiple teardown paths; closeConnection() runs at most once
* ```
*/
function once(fn) {
let called = false;
let result;
return (...args) => {
if (!called) {
called = true;
result = fn(...args);
}
return result;
};
}
//#endregion
export { once };
//# sourceMappingURL=function.js.map