Skip to content

Instantly share code, notes, and snippets.

@nicksheffield
Last active February 22, 2018 02:12
Show Gist options
  • Save nicksheffield/732ef92c5b1900c9c6308ed2cbae6e2e to your computer and use it in GitHub Desktop.
Save nicksheffield/732ef92c5b1900c9c6308ed2cbae6e2e to your computer and use it in GitHub Desktop.
An attempt at implementing a maybe monad myself
const Maybe = function(val) {
this.__value = val instanceof Maybe ? val.__value : val
}
Maybe.from = function(val) {
return new Maybe(val)
}
Maybe.none = function() {
return new Maybe()
}
Maybe.prototype = {
isPresent: function() {
return this.__value !== null && this.__value !== undefined
},
map: function(cb) {
if (this.isPresent()) {
let val = cb(this.__value)
if (val && val instanceof Maybe) {
return Maybe.from(val.__value)
} else {
return Maybe.from(val)
}
} else {
return Maybe.none()
}
},
orElse: function(val) {
return this.isPresent() ? this.__value : val
}
}
const user = {
id: 1,
name: 'bob',
email: '[email protected]',
address: {
number: '20',
street: 'Nowhere road',
town: 'Townsville',
city: 'Gotham',
country: 'The Vatican',
planet: 'Mars',
system: 'Sol',
galaxy: 'The Milky Way'
}
}
const myTown = Maybe.from(user)
.map(user => Maybe.from(user.address)) // to prove that flattening happens
.map(address => address.town)
.orElse('none')
console.log('myTown', myTown)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment