Maybe Functor pattern matching
by dimitrs_papadimitriou
HTML
<script src="https://rawgit.com/eu81273/jsfiddle-console/master/console.js"></script>
JavaScript
class Maybe {
map(f) {
return this.matchWith({
none:()=>new None(),
some:(v)=>new Some(f(v))
})
}
matchWith(pattern) {
throw new Error('You have to implement the method matchWith!');
}
}
class Some extends Maybe {
constructor(value) {
super();
this.value = value;
}
matchWith(pattern) {
return pattern.some(this.value)
}
}
class None extends Maybe {
matchWith(pattern) {
return pattern.none()
}
}
var value = new Some(2);
value
.map(x=>x+3)
.matchWith({
none:()=>console.log("none"),
some:(v)=>console.log(v)
})