Created
September 20, 2022 08:04
-
-
Save ElectricCoffee/e256e42a04e0e5ffb50ae681d69cb6c7 to your computer and use it in GitHub Desktop.
Maybe monad in TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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