initial commit

This commit is contained in:
Robin Chappatte
2024-05-21 15:56:54 +02:00
commit 1fbc9fb00f
2 changed files with 57 additions and 0 deletions

56
lib.ts Normal file
View File

@@ -0,0 +1,56 @@
interface ResultInterface<T, E> {
unwrap: () => T | E;
readonly success: boolean;
}
export class ResultSuccess<T> implements ResultInterface<T, never> {
data: T;
readonly success = true;
constructor(data: T) {
this.data = data;
}
unwrap(): T {
return this.data;
}
}
export class ResultError<E> implements ResultInterface<never, E> {
error: E;
readonly success = false;
constructor(error: E) {
this.error = error;
}
unwrap(): E {
return this.error;
}
}
export type Result<T, E> = ResultSuccess<T> | ResultError<E>;
export function ok<T = undefined>(value?: T): ResultSuccess<T>;
export function ok<T>(value: T) {
return new ResultSuccess(value);
}
export function fail<T = undefined>(error?: T): ResultError<T>;
export function fail<T>(error: T) {
return new ResultError(error);
}
export function fromPromise<T>(
promise: Promise<T>,
): Promise<Result<T, unknown>> {
return promise.then(ok).catch(fail);
}
export function catchThrow<T>(func: () => T): Result<T, unknown> {
try {
return ok(func());
} catch (error) {
return fail(error);
}
}

1
mod.ts Normal file
View File

@@ -0,0 +1 @@
export * from "./lib.ts";