Skip to content

Commit

Permalink
adds EAV helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
ybabts committed Jun 16, 2023
1 parent 0a7d570 commit 28884b6
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
export type Result<
T,
E extends Error = Error,
> = T | E;

export type CustomError<M extends string> = Error & { message: M };

export function addMsg<M extends string, E extends Error>(
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<M extends string>(message: M): CustomError<M> {
return new Error(message) as CustomError<M>;
}

export function Try<T extends (...args: any[]) => any>(
func: T,
): (...args: Parameters<T>) => ReturnType<T> | Error {
return (...args: Parameters<T>) => {
try {
return func(...args);
} catch (error) {
return error;
}
};
}

// deno-lint-ignore no-explicit-any
export function isErr<T extends Error>(value: Result<any>): value is T {
return value instanceof Error;
}

export function Ok<T>(value: Result<T>): T | null {
if (value instanceof Error) {
return null;
}
return value;
}

export function Unwrap<T>(value: Result<T>): T {
if (value instanceof Error) {
throw value;
}
return value;
}

0 comments on commit 28884b6

Please sign in to comment.