mirror of
https://github.com/Effect-TS/effect.git
synced 2026-12-04 03:35:36 +08:00
Add Match.whenFilter for Filter-backed extracting cases (#10094)
This commit is contained in:
@@ -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.
|
||||
@@ -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<R, T.UnionToIntersection<P[number]>>, ...args: Args) => Ret
|
||||
>(...args: [...patterns: ExactPatterns<R, P>, f: Fn]) => internal.whenAnd<R, P, Ret, Args, Fn>(...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<string>().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<any>,
|
||||
Fn extends (_: Pass, ...args: Args) => Ret
|
||||
>(
|
||||
filter: Filter.Filter<Input, Pass, Fail>,
|
||||
f: Fn
|
||||
) => <I, F, R extends Input, A, Pr>(
|
||||
self: Matcher<I, F, R, A, Pr, Ret, Args>
|
||||
) => Matcher<I, F, R, A | ReturnType<Fn>, Pr, Ret, Args> = internal.whenFilter
|
||||
|
||||
/**
|
||||
* Matches values based on a specified discriminant field.
|
||||
*
|
||||
|
||||
@@ -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<any>,
|
||||
Fn extends (_: Pass, ...args: Args) => Ret
|
||||
>(
|
||||
filter: Filter.Filter<Input, Pass, Fail>,
|
||||
f: Fn
|
||||
) =>
|
||||
<I, F, R extends Input, A, Pr>(
|
||||
self: Matcher<I, F, R, A, Pr, Ret, Args>
|
||||
): Matcher<I, F, R, A | ReturnType<Fn>, 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,
|
||||
|
||||
@@ -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<string>().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<string>().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)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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<string, number, string>
|
||||
declare const parseUnknown: Filter.Filter<unknown, number, unknown>
|
||||
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<number>()
|
||||
return n
|
||||
}),
|
||||
Match.orElse((input) => {
|
||||
expect(input).type.toBe<string>()
|
||||
return input
|
||||
})
|
||||
)
|
||||
).type.toBe<string | number>()
|
||||
|
||||
expect(
|
||||
Match.type<string>().pipe(
|
||||
Match.whenFilter(parseNumber, (n) => n),
|
||||
Match.option
|
||||
)
|
||||
).type.toBe<(u: string) => Option.Option<number>>()
|
||||
|
||||
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<string>().pipe(
|
||||
Match.withReturnType<string>(),
|
||||
// @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<string>().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<string>().pipe(
|
||||
Match.whenFilter(parseUnknown, (n) => n),
|
||||
Match.orElse((input) => {
|
||||
expect(input).type.toBe<string>()
|
||||
return input
|
||||
})
|
||||
)
|
||||
|
||||
Match.type<string | number>().pipe(
|
||||
Match.when(Match.string, (s) => s),
|
||||
Match.whenFilter(parseUnknown, (n) => n),
|
||||
Match.orElse((input) => {
|
||||
expect(input).type.toBe<number>()
|
||||
return input
|
||||
})
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user