UNPKG

ts-data-forge

Version:

[![npm version](https://img.shields.io/npm/v/ts-data-forge.svg)](https://www.npmjs.com/package/ts-data-forge) [![npm downloads](https://img.shields.io/npm/dm/ts-data-forge.svg)](https://www.npmjs.com/package/ts-data-forge) [![License](https://img.shields.

37 lines (34 loc) 898 B
import { isError } from '@sindresorhus/is'; import { unknownToString } from '../../../others/unknown-to-string.mjs'; import { err } from './ternary-result-err.mjs'; import { ok } from './ternary-result-ok.mjs'; /** * Wraps a potentially-throwing function in a `TernaryResult`. * * @example * * ```ts * const success = TernaryResult.fromThrowable(() => 1 + 1); * * const failure = TernaryResult.fromThrowable(() => { * throw new Error('boom'); * }); * * assert.deepStrictEqual(success, TernaryResult.ok(2)); * * assert.isTrue(TernaryResult.isErr(failure)); * ``` */ const fromThrowable = (fn) => { try { return ok(fn()); } catch (error) { if (isError(error)) { return err(error); } return err(new Error(unknownToString(error))); } }; export { fromThrowable }; //# sourceMappingURL=ternary-result-from-throwable.mjs.map