From 1d66a0f58e4ebcdf4f42c9d78f82a1ab49a2cf11 Mon Sep 17 00:00:00 2001 From: Elizabeth Hunt Date: Tue, 13 May 2025 18:58:45 -0700 Subject: snapshot! --- u/fn/either.ts | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 u/fn/either.ts (limited to 'u/fn/either.ts') diff --git a/u/fn/either.ts b/u/fn/either.ts new file mode 100644 index 0000000..eaf77fd --- /dev/null +++ b/u/fn/either.ts @@ -0,0 +1,62 @@ +import type { Mapper, Supplier } from "./mod.ts"; + +export interface IEither { + mapBoth: ( + errBranch: Mapper, + okBranch: Mapper, + ) => IEither; + flatMap: (mapper: Mapper>) => IEither; + mapRight: (mapper: Mapper) => IEither; + mapLeft: (mapper: Mapper) => IEither; +} + +export class Either implements IEither { + private constructor(private readonly err?: E, private readonly ok?: T) {} + + public mapBoth( + errBranch: Mapper, + okBranch: Mapper, + ): Either { + if (this.err) return Either.left(errBranch(this.err)); + return Either.right(okBranch(this.ok!)); + } + + public flatMap(mapper: Mapper>) { + if (this.ok) return mapper(this.ok); + return Either.left(this.err!); + } + + public mapRight(mapper: Mapper): IEither { + if (this.ok) return Either.right(mapper(this.ok)); + return Either.left(this.err!); + } + + public mapLeft(mapper: Mapper) { + if (this.err) return Either.left(mapper(this.err)); + return Either.right(this.ok!); + } + + static left(e: E) { + return new Either(e); + } + + static right(t: T) { + return new Either(undefined, t); + } + + static fromFailable(s: Supplier) { + try { + return Either.right(s()); + } catch (e) { + return Either.left(e as E); + } + } + + static async fromFailableAsync(s: Promise) { + try { + return Either.right(await s); + } catch (e) { + return Either.left(e as E); + } + } +} -- cgit v1.2.3-70-g09d2