Skip to content

Instantly share code, notes, and snippets.

@jasonblanchard
Last active April 30, 2023 17:22
Show Gist options
  • Save jasonblanchard/fbd5ebdef8ab5f1e1c16b405c9009c2c to your computer and use it in GitHub Desktop.
Save jasonblanchard/fbd5ebdef8ab5f1e1c16b405c9009c2c to your computer and use it in GitHub Desktop.

Revisions

  1. jasonblanchard revised this gist Apr 30, 2023. 1 changed file with 35 additions and 5 deletions.
    40 changes: 35 additions & 5 deletions reult.ts
    Original file line number Diff line number Diff line change
    @@ -20,14 +20,44 @@ function wrap<T extends (...args: any[]) => any>(fn: T): (...args: Parameters<T>
    }
    }

    function wrapAsync<T extends (...args: any[]) => Promise<any>>(fn: T): (...args: Parameters<T>) => Promise<Result<ReturnType<T>>> {
    return async function(...args: Parameters<T>): Promise<Result<ReturnType<T>>> {
    try {
    const value = await fn(...args);
    return {
    ok: true,
    value,
    }
    } catch (error) {
    return {
    ok: false,
    error: error as Error,
    }
    }
    }
    }

    async function doSomethingAsync(arg: string) {
    return arg;
    }

    async function main() {
    const result = wrap(JSON.parse)("asdf")
    if (!result.ok) {
    console.error("uh oh", result.error)
    return;
    // const result = wrap(JSON.parse)("asdf")
    // if (!result.ok) {
    // console.error("uh oh", result.error)
    // return;
    // }

    // console.log(result.value);

    const asyncResult = await wrapAsync(doSomethingAsync)('my arg')

    if (!asyncResult.ok) {
    console.error("uh oh async", result.error)
    return
    }

    console.log(result.value);
    console.log(asyncResult.value)
    }

    main()
  2. jasonblanchard created this gist Apr 30, 2023.
    33 changes: 33 additions & 0 deletions reult.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    type Result<T, E = Error> =
    | { ok: true; value: T }
    | { ok: false; error: E };


    function wrap<T extends (...args: any[]) => any>(fn: T): (...args: Parameters<T>) => Result<ReturnType<T>> {
    return function(...args: Parameters<T>): Result<ReturnType<T>> {
    try {
    const value = fn(...args);
    return {
    ok: true,
    value,
    }
    } catch (error) {
    return {
    ok: false,
    error: error as Error,
    }
    }
    }
    }

    async function main() {
    const result = wrap(JSON.parse)("asdf")
    if (!result.ok) {
    console.error("uh oh", result.error)
    return;
    }

    console.log(result.value);
    }

    main()