Skip to content

Instantly share code, notes, and snippets.

@goldhand
Last active February 5, 2018 22:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goldhand/5fbd1ce796a71adaef56aaf418876ba6 to your computer and use it in GitHub Desktop.
Save goldhand/5fbd1ce796a71adaef56aaf418876ba6 to your computer and use it in GitHub Desktop.
A Monad class in Flow
export default class Monad<V> {
value: V;
static of = <T>(value: T): Monad<T> => new Monad(value);
constructor(value: V) {
this.value = value;
}
get isNothing(): boolean {
return !this.value;
}
map<T>(fn: (V) => T): Monad<T | null> {
return this.isNothing
? Monad.of(null)
: Monad.of(fn(this.value));
}
join(): V | Monad<null> {
return this.isNothing
? Monad.of(null)
: this.value;
}
chain<T>(fn: (V) => T): T | Monad<null> | null {
return this.map(fn).join();
}
}
import R from 'ramda';
const nilOrEmpty = R.either(R.isNil, R.isEmpty);
export default class Monad<V> {
value: V;
static of = <T>(value: T): Monad<T> => new Monad(value);
constructor(value: V) {
this.value = value;
}
get isNothing(): boolean {
return nilOrEmpty(this.value);
}
map<T>(fn: (V) => T): Monad<T | null> {
return this.isNothing
? Monad.of(null)
: Monad.of(fn(this.value));
}
join(): V | Monad<null> {
return this.isNothing
? Monad.of(null)
: this.value;
}
chain<T>(fn: (V) => T): T | Monad<null> | null {
return this.map(fn).join();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment