summaryrefslogtreecommitdiff
path: root/utils/either.ts
blob: d21c796eb32b8126f8c08e8fcd2eee674a594c72 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
export interface IEither<E, T> {
  ok?: T;
  err?: E;
  mapBoth: <Ee, Tt>(
    errBranch: (e: E) => Ee,
    okBranch: (o: T) => Tt,
  ) => IEither<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!));
  }

  static left<E, T>(e: E) {
    return new Either<E, T>(e);
  }

  static right<E, T>(t: T) {
    return new Either<E, T>(undefined, t);
  }
}