Created
December 7, 2018 07:55
-
-
Save futantan/ed3a5080e6714e845cbc039bf43c2448 to your computer and use it in GitHub Desktop.
Maybe
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
| interface IFunctor<T> { | |
| map<U>(f: (x: T) => U): IFunctor<U>; | |
| } | |
| export class Maybe<T> implements IFunctor<T> { | |
| private readonly $value: T; | |
| static of<U>(x: U) { | |
| return new Maybe(x); | |
| } | |
| constructor(x: T) { | |
| this.$value = x; | |
| } | |
| map<U>(fn: (xx: T | undefined) => U): IFunctor<U | T> { | |
| return this.isNothing ? this! : Maybe.of(fn(this.$value)); | |
| } | |
| get isNothing() { | |
| return this.$value === null || this.$value === undefined; | |
| } | |
| toString() { | |
| return this.isNothing ? "Nothing" : `Just(${this.$value})`; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment