From 28884b670c87b378955f830b8fc64857e9051633 Mon Sep 17 00:00:00 2001 From: Tyler Mueller Date: Fri, 16 Jun 2023 01:27:35 -0500 Subject: [PATCH] adds EAV helpers --- mod.ts | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 mod.ts diff --git a/mod.ts b/mod.ts new file mode 100644 index 0000000..82b3f71 --- /dev/null +++ b/mod.ts @@ -0,0 +1,51 @@ +export type Result< + T, + E extends Error = Error, +> = T | E; + +export type CustomError = Error & { message: M }; + +export function addMsg( + error: E, + message: M, +): CustomError<`${M}\n${string}`> { + return Object.assign(error, { + message: message + + `\n${error.message.split("\n").map((line) => " " + line).join("\n")}`, + }) as CustomError<`${M}\n${string}`>; +} + +export function Err(message: M): CustomError { + return new Error(message) as CustomError; +} + +export function Try any>( + func: T, +): (...args: Parameters) => ReturnType | Error { + return (...args: Parameters) => { + try { + return func(...args); + } catch (error) { + return error; + } + }; +} + +// deno-lint-ignore no-explicit-any +export function isErr(value: Result): value is T { + return value instanceof Error; +} + +export function Ok(value: Result): T | null { + if (value instanceof Error) { + return null; + } + return value; +} + +export function Unwrap(value: Result): T { + if (value instanceof Error) { + throw value; + } + return value; +}