📝 Bind the handler-map function in every example
Each README and JSDoc example now assigns the function that takes the handler object (the factory result, or the tagged key step) to a match… variable and reuses it, so the builder is created once instead of per call.
This commit is contained in:
1 parent
c8bee95088
commit
c878e60ff2
3 files changed
+20
-7
No files matched your search
@@ -37,6 +37,9 @@ The package exports four factories. Two axes pick one:
|
||||
| `getTaggedUnionMatcher<T>()` | the value is a discriminated object and all handlers return the same type | one common `R` |
|
||||
| `getTaggedUnionMatcherW<T>()` | the value is a discriminated object and handlers return different types | union of the handlers |
|
||||
|
||||
Bind the function that takes the handler map to a `match…` variable once and
|
||||
reuse it; the examples below do this, so the builder is allocated once.
|
||||
|
||||
### Primitive-union matchers
|
||||
|
||||
`getPrimitiveUnionMatcher<T>()` takes the finite universe `T` and returns a
|
||||
@@ -46,7 +49,9 @@ matcher: a function from `T` to the common return type.
|
||||
```ts
|
||||
import { getPrimitiveUnionMatcher } from "tiny-pattern-ts";
|
||||
|
||||
const reply = getPrimitiveUnionMatcher<"yes" | "no">()({
|
||||
const matchAnswer = getPrimitiveUnionMatcher<"yes" | "no">();
|
||||
|
||||
const reply = matchAnswer({
|
||||
yes: () => "agreed",
|
||||
no: () => "declined",
|
||||
});
|
||||
@@ -58,7 +63,9 @@ Add a fallback as the second argument to leave members unhandled; the fallback
|
||||
receives the remainder:
|
||||
|
||||
```ts
|
||||
const label = getPrimitiveUnionMatcher<"yes" | "no" | "maybe">()(
|
||||
const matchLabel = getPrimitiveUnionMatcher<"yes" | "no" | "maybe">();
|
||||
|
||||
const label = matchLabel(
|
||||
{ yes: () => "agreed", no: () => "declined" },
|
||||
(other) => `not sure: ${other}`, // other: "maybe"
|
||||
);
|
||||
@@ -79,7 +86,9 @@ import { getTaggedUnionMatcher } from "tiny-pattern-ts";
|
||||
type Shape =
|
||||
{ kind: "circle"; radius: number } | { kind: "square"; side: number };
|
||||
|
||||
const area = getTaggedUnionMatcher<Shape>()("kind")({
|
||||
const matchShape = getTaggedUnionMatcher<Shape>()("kind");
|
||||
|
||||
const area = matchShape({
|
||||
circle: (s) => Math.PI * s.radius ** 2,
|
||||
square: (s) => s.side ** 2,
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user