Skip to content

Instantly share code, notes, and snippets.

@futantan
Created December 7, 2018 07:55
Show Gist options
  • Select an option

  • Save futantan/ed3a5080e6714e845cbc039bf43c2448 to your computer and use it in GitHub Desktop.

Select an option

Save futantan/ed3a5080e6714e845cbc039bf43c2448 to your computer and use it in GitHub Desktop.
Maybe
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