summaryrefslogtreecommitdiff
path: root/utils/either.ts
diff options
context:
space:
mode:
Diffstat (limited to 'utils/either.ts')
-rw-r--r--utils/either.ts29
1 files changed, 26 insertions, 3 deletions
diff --git a/utils/either.ts b/utils/either.ts
index d21c796..10e4f43 100644
--- a/utils/either.ts
+++ b/utils/either.ts
@@ -5,14 +5,37 @@ export interface IEither<E, T> {
errBranch: (e: E) => Ee,
okBranch: (o: T) => Tt,
) => IEither<Ee, Tt>;
+ mapRight: <Tt>(mapper: (t: T) => Tt) => Either<E, Tt>;
+ mapLeft: <Ee>(mapper: (e: E) => Ee) => Either<Ee, T>;
+ flatMap: <Ee extends E, Tt>(
+ mapper: (e: T) => Either<Ee, Tt>,
+ ) => Either<Ee, Tt>;
}
export class Either<E, T> implements IEither<E, T> {
private constructor(readonly err?: E, readonly ok?: T) {}
- public mapBoth<Ee, Tt>(errBranch: (e: E) => Ee, okBranch: (t: T) => Tt) {
- if (this.err) return new Either<Ee, Tt>(errBranch(this.err));
- return new Either<Ee, Tt>(undefined, okBranch(this.ok!));
+ public mapBoth<Ee, Tt>(
+ errBranch: (e: E) => Ee,
+ okBranch: (t: T) => Tt,
+ ): Either<Ee, Tt> {
+ if (this.err) return Either.left(errBranch(this.err));
+ return Either.right(okBranch(this.ok!));
+ }
+
+ public flatMap<Ee extends E, Tt>(mapper: (t: T) => Either<Ee, Tt>) {
+ if (this.ok) return mapper(this.ok);
+ return this;
+ }
+
+ public mapRight<Tt>(mapper: (t: T) => Tt): Either<E, Tt> {
+ if (this.ok) return Either.right(mapper(this.ok));
+ return Either.left(this.err!);
+ }
+
+ public mapLeft<Ee>(mapper: (e: E) => Ee): Either<Ee, T> {
+ if (this.err) return Either.left(mapper(this.err));
+ return Either.right(this.ok!);
}
static left<E, T>(e: E) {