Created
November 20, 2019 08:06
-
-
Save choegyumin/8a0a40a11501b059b58e9e0b70cd376b to your computer and use it in GitHub Desktop.
TypeScript Monads (Maybe, Just, Nothing)
This file contains 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
class Maybe<T> { | |
public value: T | null | undefined; | |
constructor(value?: T) { | |
this.value = value; | |
} | |
public fmap<R>(transform: (value: T) => R | null | undefined): Just<R> | Nothing { | |
if (this.value === undefined || this.value === null) { return new Nothing(); } | |
return Maybe.fromNullable<R>(transform(this.value)); | |
} | |
public static fromNullable<V>(value?: V | null): Just<V> | Nothing { | |
if (value === undefined || value === null) { return new Nothing(); } | |
return new Just(value); | |
} | |
public isJust(): this is Maybe<T> { | |
return false; | |
} | |
public isNothing(): this is Maybe<T> { | |
return false; | |
} | |
} | |
class Just<T> extends Maybe<T> { | |
public value: T; | |
constructor(value: T) { | |
super(); | |
this.value = value; | |
} | |
public fmap<R>(transform: (value: T) => R | null | undefined): Just<R> | Nothing { | |
return Maybe.fromNullable<R>(transform(this.value)); | |
} | |
public isJust(): this is Just<T> { | |
return true; | |
} | |
} | |
class Nothing extends Maybe<undefined> { | |
public value: undefined; | |
public fmap(transform?: any): this { | |
return this; | |
} | |
public isNothing(): this is Nothing { | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://codepen.io/choegyumin/pen/PooVXOM