Last active
April 21, 2017 15:06
-
-
Save donabrams/597ceea94944603e6b2c46f5ebdc6321 to your computer and use it in GitHub Desktop.
Monad-ish Maybe in JS
This file contains 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
var good = {a: {b: {c: 1}}} | |
console.log(new Maybe(good).bind(t=>t.a).bind(t=>t.b).bind(t=>t.c).getOrElse(2)) | |
var bad = {a: 3} | |
console.log(new Maybe(bad).bind(t=>t.a).bind(t=>t.b).bind(t=>t.c).getOrElse(2)) |
This file contains 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 None = {} | |
const isNone = (t) => t === None || t === null || typeof t === 'undefined' | |
class Maybe { | |
constructor(val) { | |
this.val = isNone(val) ? None : val | |
} | |
getOrElse(defaultVal) { | |
return this.val === None ? defaultVal : this.val | |
} | |
bind(f) { | |
const toWrap = this.val === None ? None : f(this.val)// Hmm, maybe this should just be f(this.val) ¯\_(ツ)_/¯ | |
return toWrap instanceof Maybe ? toWrap : new Maybe(toWrap) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See it live @ https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Creact%2Cstage-2&targets=&browsers=&builtIns=false&debug=false&code=const%20None%20%3D%20%7B%7D%0Aconst%20isNone%20%3D%20(t)%20%3D%3E%20t%20%3D%3D%3D%20None%20%7C%7C%20t%20%3D%3D%3D%20null%20%7C%7C%20typeof%20t%20%3D%3D%3D%20'undefined'%0A%0Aclass%20Maybe%20%7B%0A%20%20constructor(val)%20%7B%0A%20%20%20%20this.val%20%3D%20isNone(val)%20%3F%20None%20%3A%20val%0A%20%20%7D%0A%20%20getOrElse(defaultVal)%20%7B%0A%20%20%20%20return%20this.val%20%3D%3D%3D%20None%20%3F%20defaultVal%20%3A%20this.val%0A%20%20%7D%0A%20%20bind(f)%20%7B%0A%20%20%20%20const%20toWrap%20%3D%20f(this.val)%0A%20%20%20%20return%20toWrap%20instanceof%20Maybe%20%3F%20toWrap%20%3A%20new%20Maybe(toWrap)%0A%20%20%7D%0A%7D%0A%0Avar%20good%20%3D%20%7Ba%3A%20%7Bb%3A%20%7Bc%3A%201%7D%7D%7D%0A%0Aconsole.log(new%20Maybe(good).bind(t%3D%3Et.a).bind(t%3D%3Et.b).bind(t%3D%3Et.c).getOrElse(2))%0A%0Avar%20bad%20%3D%20%7Ba%3A%203%7D%0A%0Aconsole.log(new%20Maybe(bad).bind(t%3D%3Et.a).bind(t%3D%3Et.b).bind(t%3D%3Et.c).getOrElse(2))