Skip to content

Commit

Permalink
feat: add Result#from and Result#fromAsync (#267)
Browse files Browse the repository at this point in the history
  • Loading branch information
Lioness100 committed Sep 26, 2021
1 parent 9971e7c commit 300f2ed
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/lib/parsers/Result.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type * as Lexure from 'lexure';
import { isFunction, Awaited } from '@sapphire/utilities';

/**
* A type used to express computations that can fail.
Expand Down Expand Up @@ -68,3 +69,29 @@ export function isOk<T, E>(x: Result<T, E>): x is Ok<T> {
export function isErr<T, E>(x: Result<T, E>): x is Err<E> {
return !x.success;
}

/**
* Creates a {@link Result} out of a callback.
* @typeparam T The result's type.
* @typeparam E The error's type.
*/
export function from<T, E = Error>(cb: (...args: unknown[]) => T): Result<T, E> {
try {
return ok(cb());
} catch (error) {
return err(error as E);
}
}

/**
* Creates a {@link Result} out of a promise or async callback.
* @typeparam T The result's type.
* @typeparam E The error's type.
*/
export async function fromAsync<T, E = Error>(promiseOrCb: Awaited<T> | ((...args: unknown[]) => Awaited<T>)): Promise<Result<T, E>> {
try {
return ok(await (isFunction(promiseOrCb) ? promiseOrCb() : promiseOrCb));
} catch (error) {
return err(error as E);
}
}

0 comments on commit 300f2ed

Please sign in to comment.