一覧へ戻る
treyhoover/zod-pattern(新しいタブで開きます)
主要言語: TypeScript
Pattern matching utility powered by Zod schemas.
- star 数
- 4
- watcher 数
- 1
- fork 数
- 0
- issue 数
- 0
- 最終更新
- 2023/10/14
主要言語: TypeScript
Pattern matching utility powered by Zod schemas.
Pattern matching utility powered by Zod schemas
zod-pattern provides a simple, typesafe and flexible pattern matching utility based on Zod schemas. With this library, you can validate and transform data using the power of Zod, and easily handle various cases based on the shape and value of the input.
npm install zod-pattern
Define patterns using Zod schemas and corresponding results:
import { pattern } from "zod-pattern"; import { z } from "zod"; type Strength = "strong" | "medium" | "weak"; const predictionMatcher = pattern() .returnType<Strength>() .case(z.number().gte(0.8), "strong") .case(z.number().gte(0.5), "medium") .default("weak"); const result = predictionMatcher.match(0.97); // "strong"
Transform matched data on-the-fly:
const predictionMatcher = pattern() .case(z.number().gte(0.8), (value) => `strong (${value * 100}%)`) .case(z.number().gte(0.5), (value) => `medium (${value * 100}%)`) .default((value) => `weak (${value * 100}%)`); const result = predictionMatcher.match(0.97); // "strong (97%)"
Match based on partial object shapes:
const partialMatcher = pattern() .case(z.object({ key: z.string() }), ({ key }) => `Matched via key: "${key}"`) .default("not matched"); const result = partialMatcher.match({ key: "magic", unused: "value" }); // `Matched via key: "magic"`
Process and route various messages/events:
const messageMatcher = pattern() .case(textMessageSchema, handleTextMessage) .case(userUpdateSchema, handleUserUpdate) .case(connectionSchema, handleConnection) .case(errorSchema, handleError) .default((err) => new Error(`Unknown message: ${err}`));
zod-pattern is MIT licensed.