Skip to content

Instantly share code, notes, and snippets.

@choegyumin
Created November 20, 2019 08:06
Show Gist options
  • Save choegyumin/8a0a40a11501b059b58e9e0b70cd376b to your computer and use it in GitHub Desktop.
Save choegyumin/8a0a40a11501b059b58e9e0b70cd376b to your computer and use it in GitHub Desktop.
TypeScript Monads (Maybe, Just, Nothing)
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;
}
}
@choegyumin
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment