Created
November 26, 2018 13:26
-
-
Save franzwong/4aaa44219aff5ce2cea262815f5f1385 to your computer and use it in GitHub Desktop.
Js Maybe type
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
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