Skip to content

Instantly share code, notes, and snippets.

@qoomon
Last active August 27, 2024 11:25
Show Gist options
  • Save qoomon/6315daae77bcede876a9de3604a46b7b to your computer and use it in GitHub Desktop.
Save qoomon/6315daae77bcede876a9de3604a46b7b to your computer and use it in GitHub Desktop.

Revisions

  1. qoomon renamed this gist Aug 27, 2024. 1 changed file with 5 additions and 5 deletions.
    10 changes: 5 additions & 5 deletions safe.ts → resultOf.ts
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,7 @@
    function safe<T>(fn: () => T): SafeResult<T>;
    function safe<T>(fn: () => Promise<T>): Promise<SafeResult<T>>;
    function safe<T>(promise: Promise<T>): SafeResult<T>;
    function safe<T>(input: (() => T | Promise<T>) | Promise<T>): SafeResult<T> | Promise<SafeResult<T>> {
    function resultOf<T>(fn: () => T): SafeResult<T>;
    function resultOf<T>(fn: () => Promise<T>): Promise<SafeResult<T>>;
    function resultOf<T>(promise: Promise<T>): SafeResult<T>;
    function resultOf<T>(input: (() => T | Promise<T>) | Promise<T>): Result<T> | Promise<Result<T>> {
    if (typeof input === 'function') {
    try {
    const result = input()
    @@ -21,6 +21,6 @@ function safe<T>(input: (() => T | Promise<T>) | Promise<T>): SafeResult<T> | Pr
    }
    }

    type SafeResult<T> =
    type Result<T> =
    { success: true, data: T, error?: never } |
    { success: false, error: unknown, data?: never };
  2. qoomon created this gist Aug 23, 2024.
    26 changes: 26 additions & 0 deletions safe.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    function safe<T>(fn: () => T): SafeResult<T>;
    function safe<T>(fn: () => Promise<T>): Promise<SafeResult<T>>;
    function safe<T>(promise: Promise<T>): SafeResult<T>;
    function safe<T>(input: (() => T | Promise<T>) | Promise<T>): SafeResult<T> | Promise<SafeResult<T>> {
    if (typeof input === 'function') {
    try {
    const result = input()
    if (result instanceof Promise) {
    return safe(result);
    }
    return {data: result, success: true as const};
    } catch (error) {
    return {error, success: false as const};
    }
    }
    if (input instanceof Promise) {
    return input.then(
    (data) => ({data, success: true as const}),
    (error) => ({error, success: false as const})
    );
    }
    }

    type SafeResult<T> =
    { success: true, data: T, error?: never } |
    { success: false, error: unknown, data?: never };