UNPKG

@remcostoeten/fync

Version:

Unified TypeScript library for 9 popular APIs with consistent functional architecture

50 lines 1.3 kB
/** * Result type for predictable error handling * Following the pattern specified in architecture.md */ /** * Helper functions for creating and handling results */ export function success(value) { return { ok: true, value }; } export function failure(error) { return { ok: false, error }; } export function isSuccess(result) { return result.ok === true; } export function isFailure(result) { return result.ok === false; } export function unwrap(result) { if (isSuccess(result)) { return result.value; } throw new Error(typeof result.error === 'string' ? result.error : 'Operation failed'); } export function unwrapOr(result, defaultValue) { return isSuccess(result) ? result.value : defaultValue; } export function mapResult(result, fn) { if (isSuccess(result)) { return success(fn(result.value)); } return result; } export async function tryCatch(fn, errorTransform) { try { const value = await fn(); return success(value); } catch (error) { if (errorTransform) { return failure(errorTransform(error)); } if (error instanceof Error) { return failure(error.message); } return failure(String(error)); } } //# sourceMappingURL=result.js.map