Skip to content

Instantly share code, notes, and snippets.

@ElectricCoffee
Created September 20, 2022 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ElectricCoffee/e256e42a04e0e5ffb50ae681d69cb6c7 to your computer and use it in GitHub Desktop.
Save ElectricCoffee/e256e42a04e0e5ffb50ae681d69cb6c7 to your computer and use it in GitHub Desktop.
Maybe monad in TypeScript
export class Maybe<A> {
readonly kind: "Just" | "Nothing";
value?: A;
private constructor(kind: "Just" | "Nothing", value?: A) {
this.kind = kind;
this.value = value;
}
static readonly just = <A>(value: A): Maybe<A> => new Maybe("Just", value);
static readonly nothing = <A>(): Maybe<A> => new Maybe("Nothing");
get(): A {
if (this.isNothing()) {
throw new Error(`Cannot retreive value from Nothing`);
}
return this.value as A;
}
getOrDefault(fallback: A): A {
return this.isNothing() ? fallback : (this.value as A);
}
getOrElse(fn: () => A): A {
return this.isNothing() ? fn() : (this.value as A);
}
isNothing() {
return this.kind === "Nothing";
}
map<A, B>(f: (a: A) => B): Maybe<B> {
return this.isNothing()
? Maybe.nothing()
: Maybe.just(f(this.value as A));
}
flatMap<A, B>(f: (a: A) => Maybe<B>): Maybe<B> {
return this.isNothing() ? Maybe.nothing() : f(this.value as A);
}
}
export const just = Maybe.just;
export const nothing = Maybe.nothing;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment