diff options
author | Elizabeth Alexander Hunt <me@liz.coffee> | 2025-05-13 09:50:15 -0700 |
---|---|---|
committer | Elizabeth Alexander Hunt <me@liz.coffee> | 2025-05-13 09:50:15 -0700 |
commit | 2543ac8b11af11f034836591046cdb52911f9403 (patch) | |
tree | d2fa475348c9867aab2994e9914895a57db88d75 /utils/either.ts | |
parent | e49fda41176d025a671802be76c219d66167276f (diff) | |
download | ci-2543ac8b11af11f034836591046cdb52911f9403.tar.gz ci-2543ac8b11af11f034836591046cdb52911f9403.zip |
snapshot
Diffstat (limited to 'utils/either.ts')
-rw-r--r-- | utils/either.ts | 29 |
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) { |