-
Notifications
You must be signed in to change notification settings - Fork 0
/
variant.ts
93 lines (78 loc) · 2.75 KB
/
variant.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { Func, UnionToIntersection, Exact } from "./util.types.js";
type Variant<K extends string, V extends any[] = []> = {
readonly kind: K;
readonly values: Readonly<V>;
};
type VariantBranch<V, R> = V extends Variant<any, infer A> ? Func<A, R> : never;
type Matcher<V, R> = UnionToIntersection<
V extends Variant<infer K, any> ? Record<K, VariantBranch<V, R>> : never
>;
type MatcherReturn<M> = M extends Matcher<any, infer R> ? R : never;
const assertVariant = (v: any) => {
const hasType = typeof v?.kind === "string";
const hasValues = Array.isArray(v?.values);
if (!hasType || !hasValues) {
throw new TypeError(
`Expected value is not of type Variant { kind: string, values: any[] }`
);
}
};
/**
* Creates a instance of a variant with the givin kind and values.
*
* @param kind - A unique name, this name will be used as the named branch to
* execute in the match expression.
* @param values - Any data that that will be stored in the variant, this data
* will be available as arguments within the named branch of a
* match expression.
* @returns An instance of a variant.
*/
const variant = <K extends string, V extends any[]>(
kind: Exclude<K, "_">,
...values: V
): Variant<Exclude<K, "_">, V> => {
if (kind === "_") {
throw new TypeError(`variants cannot be constructed with a kind of '_'`);
}
return Object.freeze({
kind,
values,
});
};
/**
* VariantTypeClass is an abstract class used to define sum type classes which contain variants.
*/
abstract class VariantTypeClass<V extends Variant<any, any[]>> {
readonly variant: V;
constructor(variant: V) {
assertVariant(variant);
this.variant = { ...variant, values: [...variant.values] };
Object.freeze(this.variant.values);
Object.freeze(this.variant);
Object.freeze(this);
}
/**
* Executes a named branch that matches the variant passed in.
*
* @param matcher - An object containing named branches for each variant kind.
* @param catchAll - An optional catch-all branch used if you don't need to handle
* all branches independently.
* @returns The result of the named branch or catchAll that was executed.
*/
match<M extends Matcher<V, any>>(
matcher: Exact<M, V["kind"]>
): MatcherReturn<M>;
match<M extends Partial<Matcher<V, any>>, R>(
matcher: Exact<M & Record<"_", Func<[this], R>>, V["kind"] | "_">
): R | MatcherReturn<M>;
match(matcher: any) {
const func = matcher[this.variant.kind] ?? matcher._;
if (func == null) {
throw new TypeError(
`Unhandled variant ${JSON.stringify(this.variant.kind)}.`
);
}
return func(...this.variant.values);
}
}
export { variant, Variant, VariantTypeClass, VariantBranch };