|
| 1 | +// 🙏 shoutout to -> https://github.com/gvergnaud/ts-pattern |
| 2 | + |
| 3 | +type Union<a, b> = [b] extends [a] ? a : [a] extends [b] ? b : a | b |
| 4 | + |
| 5 | +type Match<T, InferredOutput = never> = { |
| 6 | + /** |
| 7 | + * if the `predicate` func returns true, the value returned by the `handler` will be the one returned when calling `otherwise` |
| 8 | + */ |
| 9 | + with: <O>( |
| 10 | + predicate: (value: T) => boolean, |
| 11 | + handler: (value: T) => O |
| 12 | + ) => Match<T, Union<InferredOutput, O>> |
| 13 | + /** |
| 14 | + * takes a function allowing one to return a fallback value in case no match were found |
| 15 | + */ |
| 16 | + otherwise: <O>(fallback: () => O) => Union<InferredOutput, O> |
| 17 | +} |
| 18 | + |
| 19 | +/** |
| 20 | + * Entry point to create some sort of a matching expression |
| 21 | + * |
| 22 | + * It returns a Match builder, on which you can chain several .with(predicate, handler) clauses |
| 23 | + * |
| 24 | + * @example |
| 25 | + * |
| 26 | + * type Status = 'idle' | 'loading' | 'success' | 'error' |
| 27 | + * |
| 28 | + * const result = match(status) |
| 29 | + * .with(s => s === 'idle', (s) => <p>is {s}</p>) // s === "idle" |
| 30 | + * .with(s => s === 'loading', (s) => <Loader />) // s === "loading" |
| 31 | + * .otherwise(() => <p>either in success or in error</p>) // s === "success" | "error" |
| 32 | + * |
| 33 | + */ |
| 34 | +/* eslint-disable fp/no-mutation, fp/no-let */ |
| 35 | +export function match<T, U = never>(value?: T) { |
| 36 | + let outputValue: any |
| 37 | + |
| 38 | + function self(passedValue: T) { |
| 39 | + const matchBuilder = {} as Match<T, U> |
| 40 | + |
| 41 | + function with_<O>( |
| 42 | + predicate: (value: T) => boolean, |
| 43 | + handler: (value: T) => O |
| 44 | + ): Match<T, Union<U, O>> { |
| 45 | + if (!outputValue && predicate(passedValue)) outputValue = handler(passedValue) |
| 46 | + |
| 47 | + return self(passedValue) as unknown as Match<T, Union<U, O>> |
| 48 | + } |
| 49 | + |
| 50 | + function otherwise<O>(fallback: () => O) { |
| 51 | + return outputValue || fallback() |
| 52 | + } |
| 53 | + |
| 54 | + matchBuilder.with = with_ |
| 55 | + matchBuilder.otherwise = otherwise |
| 56 | + |
| 57 | + return matchBuilder |
| 58 | + } |
| 59 | + |
| 60 | + return self(value as T) |
| 61 | +} |
0 commit comments