diff options
Diffstat (limited to 'u/fn/either.ts')
-rw-r--r-- | u/fn/either.ts | 31 |
1 files changed, 25 insertions, 6 deletions
diff --git a/u/fn/either.ts b/u/fn/either.ts index 12240d0..916bb71 100644 --- a/u/fn/either.ts +++ b/u/fn/either.ts @@ -5,37 +5,56 @@ export interface IEither<E, T> { errBranch: Mapper<E, Ee>, okBranch: Mapper<T, Tt>, ) => IEither<Ee, Tt>; - flatMap: <Tt>(mapper: Mapper<T, IEither<E, Tt>>) => IEither<E, Tt>; + moveRight: <Tt>(t: Tt) => IEither<E, Tt>; mapRight: <Tt>(mapper: Mapper<T, Tt>) => IEither<E, Tt>; mapLeft: <Ee>(mapper: Mapper<E, Ee>) => IEither<Ee, T>; + flatMap: <Tt>(mapper: Mapper<T, IEither<E, Tt>>) => IEither<E, Tt>; + flatMapAsync: <Tt>( + mapper: Mapper<T, Promise<IEither<E, Tt>>>, + ) => Promise<IEither<E, Tt>>; } export class Either<E, T> implements IEither<E, T> { private constructor(private readonly err?: E, private readonly ok?: T) {} + public moveRight<Tt>( + t: Tt, + ) { + return this.mapRight(() => t); + } + public mapBoth<Ee, Tt>( errBranch: Mapper<E, Ee>, okBranch: Mapper<T, Tt>, ): Either<Ee, Tt> { - if (this.err) return Either.left(errBranch(this.err)); + if (this.err !== undefined) return Either.left(errBranch(this.err)); return Either.right(okBranch(this.ok!)); } public flatMap<Tt>(mapper: Mapper<T, Either<E, Tt>>): Either<E, Tt> { - if (this.ok) return mapper(this.ok); + if (this.ok !== undefined) return mapper(this.ok); return Either.left<E, Tt>(this.err!); } public mapRight<Tt>(mapper: Mapper<T, Tt>): IEither<E, Tt> { - if (this.ok) return Either.right(mapper(this.ok)); + if (this.ok !== undefined) return Either.right(mapper(this.ok)); return Either.left<E, Tt>(this.err!); } - public mapLeft<Ee>(mapper: Mapper<E, Ee>) { - if (this.err) return Either.left<Ee, T>(mapper(this.err)); + public mapLeft<Ee>(mapper: Mapper<E, Ee>): IEither<Ee, T> { + if (this.err !== undefined) return Either.left<Ee, T>(mapper(this.err)); return Either.right<Ee, T>(this.ok!); } + public async flatMapAsync<Tt>( + mapper: Mapper<T, Promise<IEither<E, Tt>>>, + ): Promise<IEither<E, Tt>> { + if (this.err !== undefined) { + return Promise.resolve(Either.left<E, Tt>(this.err)); + } + return await mapper(this.ok!).catch((err) => Either.left<E, Tt>(err as E)); + } + static left<E, T>(e: E) { return new Either<E, T>(e); } |