From 20e3d863ed12569bb0138f484b131c8d0b87ab28 Mon Sep 17 00:00:00 2001 From: MillenniumEarl Date: Thu, 25 Feb 2021 19:06:57 +0100 Subject: [PATCH] Add classes used for better management of errors --- src/scripts/classes/result.ts | 49 +++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/scripts/classes/result.ts diff --git a/src/scripts/classes/result.ts b/src/scripts/classes/result.ts new file mode 100644 index 0000000..de86728 --- /dev/null +++ b/src/scripts/classes/result.ts @@ -0,0 +1,49 @@ +export type Result = Failure | Success; + +export class Failure { + readonly value: L; + + constructor(value: L) { + this.value = value; + } + + isFailure(): this is Failure { + return true; + } + + isSuccess(): this is Success { + return false; + } + + applyOnSuccess(_: (a: A) => B): Result { + return this as any; + } +} + +export class Success { + readonly value: A; + + constructor(value: A) { + this.value = value; + } + + isFailure(): this is Failure { + return false; + } + + isSuccess(): this is Success { + return true; + } + + applyOnSuccess(func: (a: A) => B): Result { + return new Success(func(this.value)); + } +} + +export const failure = (l: L): Result => { + return new Failure(l); +}; + +export const success = (a: A): Result => { + return new Success(a); +}; \ No newline at end of file