Skip to content

Instantly share code, notes, and snippets.

@franzwong
Created November 26, 2018 13:26
Show Gist options
  • Save franzwong/4aaa44219aff5ce2cea262815f5f1385 to your computer and use it in GitHub Desktop.
Save franzwong/4aaa44219aff5ce2cea262815f5f1385 to your computer and use it in GitHub Desktop.
Js Maybe type
const VALUE = Symbol('Value');
class Container {
constructor(x) {
this[VALUE] = x
}
map(f) {
return f(this[VALUE]);
}
}
class Functor extends Container {
static of(x) {
return new Functor(x);
}
map(f) {
return Functor.of(f(this[VALUE]));
}
}
class Nothing extends Functor {
isNothing() {
return true;
}
map(f) {
return this;
}
}
class Just extends Functor {
isNothing() {
return false;
}
map(f) {
return Maybe.of(f(this[VALUE]));
}
}
class Maybe extends Functor {
constructor(x) {
return x === undefined || x === null
? new Nothing()
: new Just(x)
}
static of(x) {
return new Maybe(x)
}
}
module.exports = {
Nothing,
Just,
Maybe
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment