import {isOk, isResult} from '../internal/result'; import type {AnyResult, ExtendedErr, ResultMatch} from './models'; // #region Functions /** * Handles a _Result_ with match callbacks * * _Available as `asyncMatchResult` and `matchResult.async`_ * * @param result _Result_ to handle * @param handler Match callbacks * @returns Matched value-_Promise_ */ export async function asyncMatchResult( result: AnyResult | Promise> | (() => Promise>), handler: ResultMatch, ): Promise; /** * Handles a _Result_ with match callbacks * * _Available as `asyncMatchResult` and `matchResult.async`_ * * @param result _Result_ to handle * @param ok Ok callback * @param error Error callback * @returns Matched value-_Promise_ */ export async function asyncMatchResult( result: AnyResult | Promise> | (() => Promise>), ok: ResultMatch['ok'], error: ResultMatch['error'], ): Promise; export async function asyncMatchResult( result: AnyResult | Promise> | (() => Promise>), first: ResultMatch | ResultMatch['ok'], error?: ResultMatch['error'], ): Promise { let value: AnyResult; if (typeof result === 'function') { value = await result(); } else if (result instanceof Promise) { value = await result; } else { value = result; } if (!isResult(value)) { throw new Error(MESSAGE_RESULT); } const hasObj = typeof first === 'object' && first !== null; const okHandler = hasObj ? first.ok : first; const errorHandler = hasObj ? first.error : error; if (isOk(value)) { return okHandler(value.value); } return errorHandler!(value.error, (value as ExtendedErr).original); } /** * Handles a _Result_ with match callbacks * * @param result _Result_ to handle * @param handler Match callbacks * @returns Matched value */ export function matchResult( result: AnyResult | (() => AnyResult), handler: ResultMatch, ): Returned; /** * Handles a _Result_ with match callbacks * * @param result _Result_ to handle * @param ok Ok callback * @param error Error callback * @returns Matched value */ export function matchResult( result: AnyResult | (() => AnyResult), ok: ResultMatch['ok'], error: ResultMatch['error'], ): Returned; export function matchResult( result: AnyResult | (() => AnyResult), first: ResultMatch | ResultMatch['ok'], error?: ResultMatch['error'], ): Returned { const value = typeof result === 'function' ? result() : result; if (!isResult(value)) { throw new Error(MESSAGE_RESULT); } const hasObj = typeof first === 'object' && first !== null; const okHandler = hasObj ? first.ok : first; const errorHandler = hasObj ? first.error : error; if (isOk(value)) { return okHandler(value.value); } return errorHandler!(value.error, (value as ExtendedErr).original); } matchResult.async = asyncMatchResult; // #endregion // #region Variables const MESSAGE_RESULT = '`result.match` expected a Result or a function that returns a Result'; // #endregion