Skip to content

Commit 300f2ed

Browse files
authored
feat: add Result#from and Result#fromAsync (#267)
1 parent 9971e7c commit 300f2ed

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/lib/parsers/Result.ts

+27
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type * as Lexure from 'lexure';
2+
import { isFunction, Awaited } from '@sapphire/utilities';
23

34
/**
45
* A type used to express computations that can fail.
@@ -68,3 +69,29 @@ export function isOk<T, E>(x: Result<T, E>): x is Ok<T> {
6869
export function isErr<T, E>(x: Result<T, E>): x is Err<E> {
6970
return !x.success;
7071
}
72+
73+
/**
74+
* Creates a {@link Result} out of a callback.
75+
* @typeparam T The result's type.
76+
* @typeparam E The error's type.
77+
*/
78+
export function from<T, E = Error>(cb: (...args: unknown[]) => T): Result<T, E> {
79+
try {
80+
return ok(cb());
81+
} catch (error) {
82+
return err(error as E);
83+
}
84+
}
85+
86+
/**
87+
* Creates a {@link Result} out of a promise or async callback.
88+
* @typeparam T The result's type.
89+
* @typeparam E The error's type.
90+
*/
91+
export async function fromAsync<T, E = Error>(promiseOrCb: Awaited<T> | ((...args: unknown[]) => Awaited<T>)): Promise<Result<T, E>> {
92+
try {
93+
return ok(await (isFunction(promiseOrCb) ? promiseOrCb() : promiseOrCb));
94+
} catch (error) {
95+
return err(error as E);
96+
}
97+
}

0 commit comments

Comments
 (0)