Created
November 15, 2023 15:18
-
-
Save sasajib/687a152d92c6fed65e1d2a2357a6a765 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class Either<L, R> { | |
constructor(private left: L | null, private right: R | null) {} | |
static left<L, R>(value: L): Either<L, R> { | |
return new Either<L, R>(value, null); | |
} | |
static right<L, R>(value: R): Either<L, R> { | |
return new Either<L, R>(null, value); | |
} | |
isLeft(): boolean { | |
return this.left !== null; | |
} | |
isRight(): boolean { | |
return this.right !== null; | |
} | |
getLeft(): L { | |
if (this.isLeft()) { | |
return this.left as L; | |
} | |
throw new Error("Attempted to get Left value from a Right"); | |
} | |
getRight(): R { | |
if (this.isRight()) { | |
return this.right as R; | |
} | |
throw new Error("Attempted to get Right value from a Left"); | |
} | |
map<T>(f: (right: R) => T): Either<L, T> { | |
if (this.isRight()) { | |
return Either.right<L, T>(f(this.getRight())); | |
} else { | |
return Either.left<L, T>(this.getLeft() as L); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment