import { ensureError } from './errors'; export type ResultOk = { ok: true; result: T }; export type ResultError = { ok: false; error: E }; export type Result = ResultOk | ResultError; export const createResultOk = (data: T): ResultOk => ({ ok: true, result: data, }); export const createResultError = (error: E): ResultError => ({ ok: false, error, }); /** * Executes the given function and converts it to a Result object. * * @example * const result = toResult(() => fs.writeFileSync('file.txt', 'Hello, World!')); */ export const toResult = (fn: () => T): Result => { try { return createResultOk(fn()); } catch (e) { const error = ensureError(e); return createResultError(error as E); } };