From 1ab20482ab37d7962c8e69701163270e687df3ca Mon Sep 17 00:00:00 2001 From: Elizabeth Alexander Hunt Date: Thu, 15 May 2025 23:39:29 -0700 Subject: more snapshot --- u/fn/either.ts | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) (limited to 'u/fn/either.ts') 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 { errBranch: Mapper, okBranch: Mapper, ) => IEither; - flatMap: (mapper: Mapper>) => IEither; + moveRight: (t: Tt) => IEither; mapRight: (mapper: Mapper) => IEither; mapLeft: (mapper: Mapper) => IEither; + flatMap: (mapper: Mapper>) => IEither; + flatMapAsync: ( + mapper: Mapper>>, + ) => Promise>; } export class Either implements IEither { private constructor(private readonly err?: E, private readonly ok?: T) {} + public moveRight( + t: Tt, + ) { + return this.mapRight(() => t); + } + public mapBoth( errBranch: Mapper, okBranch: Mapper, ): Either { - 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(mapper: Mapper>): Either { - if (this.ok) return mapper(this.ok); + if (this.ok !== undefined) return mapper(this.ok); return Either.left(this.err!); } public mapRight(mapper: Mapper): IEither { - if (this.ok) return Either.right(mapper(this.ok)); + if (this.ok !== undefined) return Either.right(mapper(this.ok)); return Either.left(this.err!); } - public mapLeft(mapper: Mapper) { - if (this.err) return Either.left(mapper(this.err)); + public mapLeft(mapper: Mapper): IEither { + if (this.err !== undefined) return Either.left(mapper(this.err)); return Either.right(this.ok!); } + public async flatMapAsync( + mapper: Mapper>>, + ): Promise> { + if (this.err !== undefined) { + return Promise.resolve(Either.left(this.err)); + } + return await mapper(this.ok!).catch((err) => Either.left(err as E)); + } + static left(e: E) { return new Either(e); } -- cgit v1.2.3-70-g09d2