Created
February 1, 2023 14:09
-
-
Save zhy0216/2438fc46cb637cba842075519d5a859b to your computer and use it in GitHub Desktop.
typescript Either<L, R>
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 abstract class Either<L, R> { | |
left!: L; | |
right!: R; | |
static Right = <T>(v: T) => new Right(v); | |
static Left = <T>(v: T) => new Left(v); | |
abstract map<T>(f: (a: R) => T): Either<L, T>; | |
abstract flatMap<T>(f: (a: R) => Either<L, T>): Either<L, T>; | |
abstract orElse<T>(a: Either<L, T>): Either<L, R>; | |
abstract get(): R; | |
abstract getOrElse(v: R): R; | |
} | |
export class Left<L> extends Either<L, any> { | |
constructor(value: L) { | |
super(); | |
this.left = value; | |
} | |
flatMap<T>(f: (a: any) => Either<L, T>): Either<L, T> { | |
return this; | |
} | |
map<T>(f: (a: any) => T): Either<L, T> { | |
return this; | |
} | |
orElse<T>(a: Either<L, T>): Either<L, any> { | |
return a; | |
} | |
get(): any { | |
throw new Error(this.toString()); | |
} | |
getOrElse(v: any) { | |
return v; | |
} | |
override toString() { | |
return this.left?.toString() ?? 'something wrong'; | |
} | |
} | |
export class Right<R> extends Either<any, R> { | |
constructor(value: R) { | |
super(); | |
this.right = value; | |
} | |
flatMap<T>(f: (a: R) => Either<any, T>): Either<any, T> { | |
return f(this.right); | |
} | |
map<T>(f: (a: R) => T): Either<any, T> { | |
return Either.Right(f(this.right)); | |
} | |
orElse<T>(a: Either<any, T>): Either<any, R> { | |
return this; | |
} | |
get() { | |
return this.right; | |
} | |
getOrElse(v: R) { | |
return this.right; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment