UNPKG

tiinvo

Version:

A library of types and utilities for your TypeScript and JavaScript projects

65 lines (64 loc) 1.67 kB
import { catchableAsync, catchableSync } from './Functors.js'; /** * Uses the `Functors.Catchable<f>` to return a wrapped function `f`. * * If the function `f` throws internally, then the functors' catch function is called, otherwise returns `f` output * * @example * * ```ts * import { Catch, Functors, Num } from 'tiinvo' * * function catchy(arg: number) { * if (Num.isEven(arg)) { * throw new TypeError("I expected an odd number :(") * } * * return arg; * } * * const c: Functors.CatchableModule<typeof catchy> = { * [Functors.catchableSync]() { * return { * catch: (_error, args) => args[0] - 1, * func: catchy, * } * } * } * * const catched = Catch.make(c); * * catched(10) // 9 * catched(7) // 7 * ``` * * @template F the function to catch * @param catchable the CatchableModule<F> * @returns a unary function * @since 4.0.0 */ export const make = (catchable) => { const modAsync = catchable[catchableAsync]?.(); const modSync = catchable[catchableSync]?.(); if (modAsync) { return (async (...args) => { try { return await modAsync.func.apply(null, args); } catch (error) { return await modAsync.catch(error, args); } }); } else if (modSync) { return ((...args) => { try { return modSync.func.apply(null, args); } catch (error) { return modSync.catch(error, args); } }); } throw new Error(`Invalid Catchable passed`); };