import { assert, isFunction } from '../validation/index.ts'; type ResultTuple = [T, null] | [null, Error]; /** * Error tuple, go-style. * * @param fn async function to run * * @example * * const [result, error] = await attempt(async () => { * return 'hello'; * }); * * if (error) { * console.error(error); * } * * console.log(result); */ export const attempt = async Promise>(fn: T): Promise>>> => { assert(isFunction(fn), 'fn must be a function'); try { return [await fn(), null] } catch (e) { return [null, e as Error] } } /** * Synchronous error tuple, go-style. * * @example * * const [result, error] = attemptSync(() => { * return 'hello'; * }); * * if (error) { * console.error(error); * } * * console.log(result); */ export const attemptSync = any>(fn: T): ResultTuple> => { assert(isFunction(fn), 'fn must be a function'); try { return [fn(), null] } catch (e) { return [null, e as Error] } }