summaryrefslogtreecommitdiff
path: root/u/fn
diff options
context:
space:
mode:
authorElizabeth Alexander Hunt <me@liz.coffee>2025-05-15 23:39:29 -0700
committerElizabeth Alexander Hunt <me@liz.coffee>2025-05-15 23:40:00 -0700
commit1ab20482ab37d7962c8e69701163270e687df3ca (patch)
treef0aaac54f8c23269fdeb2bca6f22e296a9e0559f /u/fn
parent3a3fb9c8ab0c798a278f76d40de216fa96f6e2c4 (diff)
downloadci-1ab20482ab37d7962c8e69701163270e687df3ca.tar.gz
ci-1ab20482ab37d7962c8e69701163270e687df3ca.zip
more snapshot
Diffstat (limited to 'u/fn')
-rw-r--r--u/fn/either.ts31
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);
}