-
Notifications
You must be signed in to change notification settings - Fork 2
/
result.ts
41 lines (33 loc) · 801 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
// A generic result type that can express a possibly failed result.
export type Error = {
readonly ok: false
readonly error: string
readonly value?: undefined
}
export type Ok<T> = {
readonly ok: true
readonly error?: undefined
readonly value: T
}
export type Result<T> = Ok<T> | Error
export function ok<T>(value: T): Result<T> {
return { ok: true, value }
}
export function error(error: string): Error {
return { ok: false, error }
}
function unwrap<T>(result: Result<T>): T {
if (result.ok) {
return result.value
}
throw new Error(result.error)
}
export function coroutine<T>(
fn: (unwrap: <U>(result: Result<U>) => U) => Result<T>,
) {
try {
return ok(fn(unwrap))
} catch (err) {
return error(err instanceof Error ? err.message : String(err))
}
}