-
Notifications
You must be signed in to change notification settings - Fork 0
/
result.ts
43 lines (40 loc) · 987 Bytes
/
result.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
import { type FnOnce, IDENTIFIER } from "./_common.ts";
export interface Result<Ok, Err> {
[IDENTIFIER]: "result";
unwrap(): Ok;
unwrapErr(): Err;
unwrapOr<T>(val: T): Ok | T;
unwrapOrElse<T>(fnOnce: FnOnce<T>): Ok | T;
readonly isErr: boolean;
readonly isOk: boolean;
}
export function Ok<Ok>(val: Ok): Result<Ok, unknown> {
return {
[IDENTIFIER]: "result",
unwrap: () => val,
unwrapErr() {
throw new Error("Tried to unwrap error when variant is Ok");
},
unwrapOr(_) {
return this.unwrap();
},
unwrapOrElse(_) {
return this.unwrap();
},
isErr: false,
isOk: true,
};
}
export function Err<Err>(val: Err): Result<unknown, Err> {
return {
[IDENTIFIER]: "result",
unwrap() {
throw new Error("Tried to unwrap value when variant is Err");
},
unwrapErr: () => val,
unwrapOr: <T>(v: T) => v,
unwrapOrElse: <T>(fnOnce: FnOnce<T>) => fnOnce(),
isErr: true,
isOk: false,
};
}