Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/once-function.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"wellcrafted": minor
---

Add `once` at the new `wellcrafted/function` subpath. `once(fn)` runs the wrapped function at most once: the first call invokes it and caches the result, and every later call returns that cached result while ignoring any arguments passed after the first. It is a dependency-free combinator for idempotent disposal and lazy one-time initialization.
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@
"types": "./dist/brand.d.ts",
"import": "./dist/brand.js"
},
"./function": {
"types": "./dist/function.d.ts",
"import": "./dist/function.js"
},
"./query": {
"types": "./dist/query/index.d.ts",
"import": "./dist/query/index.js"
Expand Down
60 changes: 60 additions & 0 deletions src/function.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { describe, expect, expectTypeOf, it } from "bun:test";
import { once } from "./function.js";

describe("once", () => {
// =============================================================================
// Runs at most once
// =============================================================================

it("runs the wrapped fn only on the first call", () => {
let calls = 0;
const wrapped = once(() => {
calls++;
});
wrapped();
wrapped();
wrapped();
expect(calls).toBe(1);
});

// =============================================================================
// Caches the first result
// =============================================================================

it("returns the first result on every later call", () => {
let n = 0;
const wrapped = once(() => ++n);
expect(wrapped()).toBe(1);
expect(wrapped()).toBe(1);
expect(n).toBe(1);
});

it("caches the same object reference across calls", () => {
const wrapped = once(() => ({ id: Math.random() }));
expect(wrapped()).toBe(wrapped());
});

// =============================================================================
// Later arguments are ignored
// =============================================================================

it("passes the first call args and ignores later ones", () => {
const seen: number[] = [];
const wrapped = once((x: number) => {
seen.push(x);
return x;
});
expect(wrapped(1)).toBe(1);
expect(wrapped(2)).toBe(1);
expect(seen).toEqual([1]);
});

// =============================================================================
// Types: the wrapper mirrors the wrapped function's signature
// =============================================================================

it("preserves the wrapped function's parameter and return types", () => {
const wrapped = once((a: number, b: string) => `${a}${b}`);
expectTypeOf(wrapped).toEqualTypeOf<(a: number, b: string) => string>();
});
});
43 changes: 43 additions & 0 deletions src/function.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* 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
* ```
*/
export function once<TArgs extends readonly unknown[], TReturn>(
fn: (...args: TArgs) => TReturn,
): (...args: TArgs) => TReturn {
let called = false;
let result: TReturn;
return (...args: TArgs): TReturn => {
if (!called) {
called = true;
result = fn(...args);
}
return result;
};
}
1 change: 1 addition & 0 deletions tsdown.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export default defineConfig({
"src/logger/index.ts",
"src/json.ts",
"src/brand.ts",
"src/function.ts",
"src/query/index.ts",
"src/standard-schema/index.ts",
"src/testing.ts",
Expand Down
Loading