From cd531d2ec79a374c582faa44edefc451be8974db Mon Sep 17 00:00:00 2001 From: effect-bot <129879685+effect-bot@users.noreply.github.com> Date: Fri, 30 Oct 2026 09:52:44 +1300 Subject: [PATCH] Add Match.whenFilter for Filter-backed extracting cases (#10094) --- .changeset/match-when-filter.md | 5 ++ packages/effect/src/Match.ts | 62 ++++++++++++++++++++++++ packages/effect/src/internal/matcher.ts | 45 +++++++++++++++++ packages/effect/test/Match.test.ts | 64 ++++++++++++++++++++++++- packages/effect/typetest/Match.tst.ts | 64 ++++++++++++++++++++++++- 5 files changed, 237 insertions(+), 3 deletions(-) create mode 100644 .changeset/match-when-filter.md diff --git a/.changeset/match-when-filter.md b/.changeset/match-when-filter.md new file mode 100644 index 0000000000..bc1b2d6981 --- /dev/null +++ b/.changeset/match-when-filter.md @@ -0,0 +1,5 @@ +--- +"effect": minor +--- + +Add `Match.whenFilter`, a case that runs a `Filter` once and passes its extracted value to the handler, falling through with the original input when the filter fails. diff --git a/packages/effect/src/Match.ts b/packages/effect/src/Match.ts index 886b18e738..d44c8a821e 100644 --- a/packages/effect/src/Match.ts +++ b/packages/effect/src/Match.ts @@ -11,6 +11,7 @@ * @stability stable * @since 4.0.0 */ +import type * as Filter from "./Filter.ts" import * as internal from "./internal/matcher.ts" import type * as Option from "./Option.ts" import type { Pipeable } from "./Pipeable.ts" @@ -817,6 +818,67 @@ export const whenAnd: < Fn extends (_: Types.WhenMatch>, ...args: Args) => Ret >(...args: [...patterns: ExactPatterns, f: Fn]) => internal.whenAnd(...args) +/** + * Defines a case that extracts a value with a `Filter`. + * + * **When to use** + * + * Use when a case both decides whether the input matches and computes a value + * the handler needs, such as parsing or normalizing the input, so the work is + * not repeated inside the handler. + * + * **Details** + * + * The filter runs once when the case is reached, and never if an earlier case + * already matched. On success, the handler receives the filter's pass value. + * On failure, the failure value is discarded and matching continues with the + * original input. + * + * Because a filter can reject any input, this case does not remove anything + * from the remaining input, so it never makes {@link exhaustive} valid on its + * own. + * + * **Example** (Matching on a parsed value) + * + * ```ts import.meta.vitest + * import { Filter, Match, Option } from "effect" + * + * const domainLabel = Filter.fromPredicateOption((query: string) => { + * const label = query.trim().toLowerCase() + * return label.length > 0 ? Option.some(label) : Option.none() + * }) + * + * const describeQuery = Match.type().pipe( + * Match.when("", () => "empty"), + * Match.whenFilter(domainLabel, (label) => `search:${label}`), + * Match.orElse(() => "invalid") + * ) + * + * describeQuery(" ACME ") // => "search:acme" + * describeQuery("") // => "empty" + * describeQuery(" ") // => "invalid" + * ``` + * + * @see {@link when} for matching a pattern and receiving the original input + * + * @stability stable + * @category defining patterns + * @since 4.2.0 + */ +export const whenFilter: < + Input, + Pass, + Fail, + Ret, + Args extends Array, + Fn extends (_: Pass, ...args: Args) => Ret +>( + filter: Filter.Filter, + f: Fn +) => ( + self: Matcher +) => Matcher, Pr, Ret, Args> = internal.whenFilter + /** * Matches values based on a specified discriminant field. * diff --git a/packages/effect/src/internal/matcher.ts b/packages/effect/src/internal/matcher.ts index 063eb6fb51..1907b28763 100644 --- a/packages/effect/src/internal/matcher.ts +++ b/packages/effect/src/internal/matcher.ts @@ -1,3 +1,4 @@ +import type * as Filter from "../Filter.ts" import { dual, identity } from "../Function.ts" import type { Case, @@ -311,6 +312,50 @@ export const when = < Args > => (self as any).add(makeWhen(makePredicate(pattern), f as any)) +/** @internal */ +export const whenFilter = < + Input, + Pass, + Fail, + Ret, + Args extends Array, + Fn extends (_: Pass, ...args: Args) => Ret +>( + filter: Filter.Filter, + f: Fn +) => +( + self: Matcher +): Matcher, Pr, Ret, Args> => { + // Caches the result of a successful `guard` for the `evaluate` call that + // follows it, so the filter runs once per match. `evaluate` consumes the + // cache, and re-runs the filter when called without a matching `guard`. + let guarded: { readonly input: unknown; readonly pass: Pass } | undefined + return (self as any).add(makeWhen( + (input) => { + guarded = undefined + const result = filter(input as Input) + if (Result.isFailure(result)) { + return false + } + guarded = { input, pass: result.success } + return true + }, + (input, ...args) => { + const cached = guarded + guarded = undefined + if (cached !== undefined && Object.is(cached.input, input)) { + return f(cached.pass, ...args as Args) + } + const result = filter(input as Input) + if (Result.isFailure(result)) { + throw new Error("effect/Match/whenFilter: input did not match the filter") + } + return f(result.success, ...args as Args) + } + )) +} + /** @internal */ export const whenOr = < R, diff --git a/packages/effect/test/Match.test.ts b/packages/effect/test/Match.test.ts index 2758ec4999..69132e8117 100644 --- a/packages/effect/test/Match.test.ts +++ b/packages/effect/test/Match.test.ts @@ -1,6 +1,6 @@ import { describe, it } from "@effect/vitest" -import { Match, pipe } from "effect" -import { strictEqual } from "./utils/assert.ts" +import { Filter, Match, Option, pipe } from "effect" +import { assertFalse, assertTrue, strictEqual, throws } from "./utils/assert.ts" describe("Match", () => { it("fn keeps the selector arguments", () => { @@ -105,4 +105,64 @@ describe("Match", () => { strictEqual(match([1, 2]), "hit") strictEqual(match([1, 2, 3]), "hit") }) + + it("whenFilter passes the extracted value and otherwise falls through with the original input", () => { + let calls = 0 + const queryToDomainLabel = Filter.fromPredicateOption((query: string) => { + calls++ + const label = query.trim().toLowerCase() + return label.length > 0 ? Option.some(label) : Option.none() + }) + const describeQuery = (query: string) => + Match.value(query).pipe( + Match.when("", () => "empty"), + Match.whenFilter(queryToDomainLabel, (label) => `search:${label}`), + Match.orElse((query) => `invalid:[${query}]`) + ) + + strictEqual(describeQuery(" ACME "), "search:acme") + strictEqual(calls, 1) + strictEqual(describeQuery(""), "empty") + strictEqual(calls, 1) + strictEqual(describeQuery(" "), "invalid:[ ]") + strictEqual(calls, 2) + + const describeType = Match.type().pipe( + Match.whenFilter(queryToDomainLabel, (label) => `search:${label}`), + Match.orElse((query) => `invalid:[${query}]`) + ) + + strictEqual(describeType(" ACME "), "search:acme") + strictEqual(describeType(" "), "invalid:[ ]") + strictEqual(calls, 4) + }) + + it("whenFilter cases keep the guard and evaluate contract of Case", () => { + let calls = 0 + let fail = false + const matcher = Match.type().pipe( + Match.whenFilter( + Filter.fromPredicateOption((s: string) => { + calls++ + if (fail) throw new Error("boom") + return s === "" ? Option.none() : Option.some(s.length) + }), + (n) => n * 10 + ) + ) + assertTrue(matcher._tag === "TypeMatcher") + const [_case] = matcher.cases + + assertTrue(_case.guard("abc")) + strictEqual(_case.evaluate("abc"), 30) + assertFalse(_case.guard("")) + + // a throwing guard must not leave an earlier extraction behind + assertTrue(_case.guard("abc")) + fail = true + throws(() => _case.guard("abc")) + fail = false + strictEqual(_case.evaluate("abc"), 30) + strictEqual(calls, 5) + }) }) diff --git a/packages/effect/typetest/Match.tst.ts b/packages/effect/typetest/Match.tst.ts index 3a9f69fc45..6cc831e687 100644 --- a/packages/effect/typetest/Match.tst.ts +++ b/packages/effect/typetest/Match.tst.ts @@ -1,4 +1,4 @@ -import { Effect, Match, Option, pipe, type Result, Schema } from "effect" +import { Effect, type Filter, Match, Option, pipe, type Result, Schema } from "effect" import { describe, expect, it } from "tstyche" type Closed = { readonly _tag: "Closed" } @@ -14,6 +14,9 @@ declare const taggedInput: declare const discriminatedInput: | { readonly kind: "A"; readonly a: string } | { readonly kind: "B"; readonly b: number } +declare const text: string +declare const parseNumber: Filter.Filter +declare const parseUnknown: Filter.Filter declare const status: "draft" | "review" | "published" declare const renamedTransfer: { readonly _tag: "Transfer"; readonly renamedValue: "foo" } | null @@ -550,4 +553,63 @@ describe("Match", () => { }) ) }) + + it("whenFilter passes the filter's Pass type and keeps the remaining input", () => { + expect( + Match.value(text).pipe( + Match.whenFilter(parseNumber, (n) => { + expect(n).type.toBe() + return n + }), + Match.orElse((input) => { + expect(input).type.toBe() + return input + }) + ) + ).type.toBe() + + expect( + Match.type().pipe( + Match.whenFilter(parseNumber, (n) => n), + Match.option + ) + ).type.toBe<(u: string) => Option.Option>() + + expect( + Match.fn((_prefix: boolean, value: string) => value).pipe( + Match.whenFilter(parseNumber, (_n, prefix) => prefix), + Match.orElse((_value, prefix) => !prefix) + ) + ).type.toBe<(prefix: boolean, value: string) => boolean>() + + Match.type().pipe( + Match.withReturnType(), + // @ts-expect-error is not assignable to + Match.whenFilter(parseNumber, (n) => n) + ) + + // a filter can reject any input, so it never proves exhaustiveness + const incomplete = Match.type().pipe(Match.whenFilter(parseNumber, (n) => n)) + // @ts-expect-error Argument of type + Match.exhaustive(incomplete) + }) + + it("whenFilter keeps the matcher's remaining input for broader filters", () => { + Match.type().pipe( + Match.whenFilter(parseUnknown, (n) => n), + Match.orElse((input) => { + expect(input).type.toBe() + return input + }) + ) + + Match.type().pipe( + Match.when(Match.string, (s) => s), + Match.whenFilter(parseUnknown, (n) => n), + Match.orElse((input) => { + expect(input).type.toBe() + return input + }) + ) + }) })