|
1 |
| -import { err, ok, type Result } from "./result"; |
| 1 | +import { err, isErr, ok, type Result } from "./result"; |
2 | 2 |
|
3 | 3 | /**
|
4 | 4 | * Run a function, catching whatever's thrown and return a Result.
|
@@ -35,13 +35,11 @@ export function tryUnknownFn<T, E = unknown>(
|
35 | 35 | fn: () => T | Promise<T>,
|
36 | 36 | ): Result<T, E> | Promise<Result<T, E>> {
|
37 | 37 | try {
|
38 |
| - const result = fn(); |
39 |
| - if (result instanceof Promise) { |
40 |
| - return result |
41 |
| - .then((value) => ok(value)) |
42 |
| - .catch((error) => err(error as E)); |
| 38 | + const r = fn(); |
| 39 | + if (r instanceof Promise) { |
| 40 | + return r.then((value) => ok(value)).catch((error) => err(error as E)); |
43 | 41 | }
|
44 |
| - return ok(result as T); |
| 42 | + return ok(r as T); |
45 | 43 | } catch (error) {
|
46 | 44 | return err(error as E);
|
47 | 45 | }
|
@@ -75,31 +73,27 @@ export function tryFn<T, E = Error>(fn: () => T): Result<T, E>;
|
75 | 73 | export function tryFn<T, E = Error>(
|
76 | 74 | fn: () => T | Promise<T>,
|
77 | 75 | ): Result<T, E> | Promise<Result<T, E>> {
|
78 |
| - const result = tryUnknownFn(fn); |
| 76 | + const r = tryUnknownFn(fn); |
79 | 77 |
|
80 |
| - if (result instanceof Promise) { |
81 |
| - return result.then((res) => { |
82 |
| - if (res._tag === "Ok") { |
83 |
| - return res; |
84 |
| - } |
85 |
| - if (res._tag === "Err") { |
| 78 | + if (r instanceof Promise) { |
| 79 | + return r.then((res) => { |
| 80 | + if (isErr(res)) { |
86 | 81 | if (res.error instanceof Error) {
|
87 | 82 | return err(res.error as E);
|
88 | 83 | }
|
89 | 84 | return err(new Error(String(res.error)) as E);
|
90 | 85 | }
|
| 86 | + |
91 | 87 | return res;
|
92 | 88 | });
|
93 | 89 | }
|
94 | 90 |
|
95 |
| - if (result._tag === "Ok") { |
96 |
| - return result as Result<T, E>; |
97 |
| - } |
98 |
| - if (result._tag === "Err") { |
99 |
| - if (result.error instanceof Error) { |
100 |
| - return err(result.error as E); |
| 91 | + if (isErr(r)) { |
| 92 | + if (r.error instanceof Error) { |
| 93 | + return err(r.error as E); |
101 | 94 | }
|
102 |
| - return err(new Error(String(result.error)) as E); |
| 95 | + return err(new Error(String(r.error)) as E); |
103 | 96 | }
|
104 |
| - return result as Result<T, E>; |
| 97 | + |
| 98 | + return r as Result<T, E>; |
105 | 99 | }
|
0 commit comments