Skip to content

Instantly share code, notes, and snippets.

@donabrams
Last active January 23, 2026 22:13
Show Gist options
  • Select an option

  • Save donabrams/597ceea94944603e6b2c46f5ebdc6321 to your computer and use it in GitHub Desktop.

Select an option

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)
}
}
@jt3k
Copy link

jt3k commented Jan 23, 2026

If there is no difference, then why write longer?? )))

var obj = {a: {b: {c: 1}}};
var value = obj?.a?.b?.vvv ?? 'else';

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment