Skip to content

Instantly share code, notes, and snippets.

@donabrams
Last active April 21, 2017 15:06
Show Gist options
  • Save donabrams/597ceea94944603e6b2c46f5ebdc6321 to your computer and use it in GitHub Desktop.
Save donabrams/597ceea94944603e6b2c46f5ebdc6321 to your computer and use it in GitHub Desktop.
Monad-ish Maybe in JS
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))
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)
}
}