✅ Assert README example results
Assign every documented matcher result to a variable and assert it with `assert.equal`, so the compiled README doc-tests verify behavior instead of merely running the code. The examples import `node:assert` themselves to stay copy-pasteable; the generator now merges that import into its prelude assert rather than rejecting it (only `node:test` remains reserved).
This commit is contained in:
1 parent
30d97a9209
commit
d0dd8641f2
3 files changed
+35
-13
No files matched your search
@@ -47,6 +47,7 @@ builder. Calling the builder with a handler map keyed by `T`'s members returns a
|
||||
matcher: a function from `T` to the common return type.
|
||||
|
||||
```ts
|
||||
import { strict as assert } from "node:assert";
|
||||
import { getPrimitiveUnionMatcher } from "tiny-pattern-ts";
|
||||
|
||||
const matchAnswer = getPrimitiveUnionMatcher<"yes" | "no">();
|
||||
@@ -56,13 +57,15 @@ const reply = matchAnswer({
|
||||
no: () => "declined",
|
||||
});
|
||||
|
||||
reply("yes"); // "agreed"
|
||||
const answer = reply("yes");
|
||||
assert.equal(answer, "agreed");
|
||||
```
|
||||
|
||||
Add a fallback as the second argument to leave members unhandled; the fallback
|
||||
receives the remainder:
|
||||
|
||||
```ts
|
||||
import { strict as assert } from "node:assert";
|
||||
import { getPrimitiveUnionMatcher } from "tiny-pattern-ts";
|
||||
|
||||
const matchLabel = getPrimitiveUnionMatcher<"yes" | "no" | "maybe">();
|
||||
@@ -71,6 +74,12 @@ const label = matchLabel(
|
||||
{ yes: () => "agreed", no: () => "declined" },
|
||||
(other) => `not sure: ${other}`, // other: "maybe"
|
||||
);
|
||||
|
||||
const answer = label("yes");
|
||||
assert.equal(answer, "agreed");
|
||||
|
||||
const fallback = label("maybe");
|
||||
assert.equal(fallback, "not sure: maybe");
|
||||
```
|
||||
|
||||
`getPrimitiveUnionMatcherW` is the same builder, but the matcher's return type
|
||||
@@ -83,6 +92,7 @@ function takes the discriminant property's name and returns the handler-map
|
||||
builder, keyed by that property's tags.
|
||||
|
||||
```ts
|
||||
import { strict as assert } from "node:assert";
|
||||
import { getTaggedUnionMatcher } from "tiny-pattern-ts";
|
||||
|
||||
type Shape =
|
||||
@@ -95,7 +105,11 @@ const area = matchShape({
|
||||
square: (s) => s.side ** 2,
|
||||
});
|
||||
|
||||
area({ kind: "circle", radius: 2 });
|
||||
const circleArea = area({ kind: "circle", radius: 2 });
|
||||
assert.equal(circleArea, Math.PI * 4);
|
||||
|
||||
const squareArea = area({ kind: "square", side: 3 });
|
||||
assert.equal(squareArea, 9);
|
||||
```
|
||||
|
||||
`getTaggedUnionMatcherW` is the widening counterpart, exactly as in the
|
||||
|
||||
Reference in new issue
Block a user