Created
January 6, 2019 18:52
-
-
Save andrewthauer/b105a3612530faa1db5cc0d3eaeb96d2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 R = require('ramda'), | |
prop = R.prop, | |
path = R.path, | |
curry = R.curry; | |
// Test Data | |
let user1 = { | |
id: 1, | |
login: 'andrew', | |
details: { | |
address: { | |
city: 'toronto' | |
} | |
} | |
} | |
let user2 = { | |
id: 1, | |
login: 'andrew', | |
details: { | |
address: null | |
} | |
} | |
/** | |
* Maybe monad | |
* | |
* @class Maybe | |
*/ | |
class Maybe { | |
constructor(value) { | |
this.value = value | |
} | |
static of(value) { | |
return new Maybe(value); | |
} | |
get isNothing() { | |
return (this.value === null || this.value === undefined); | |
} | |
map(f) { | |
return this.isNothing ? Maybe.of(null) : Maybe.of(f(this.value)); | |
} | |
join() { | |
return this.value; | |
} | |
chain(f) { | |
return this.map(f).join(); | |
} | |
orElse(defaultValue) { | |
return this.isNothing ? Maybe.of(defaultValue) : this; | |
} | |
ap(someOtherMaybe) { | |
return someOtherMaybe.map(this.value); | |
} | |
} | |
// --------------------- | |
// Tests | |
Maybe.of(34).map(R.identity).chain(R.identity) /*?*/ | |
var a = Maybe.of(user2) | |
.map(prop('details')) | |
.map(prop('address')) | |
.map(prop('city')) | |
.chain(R.identity) /*?*/ | |
.join() | |
Maybe.of(user2) | |
.map(path(['details', 'address', 'city'])) | |
.chain(R.identity) /*?*/ | |
// .join() /*?*/ | |
// Maybe.of(user1) | |
// .map(path(['details', 'address', 'city'])) | |
// .chain(Maybe.of(R.identity)) /*?*/ | |
// .orElse(1) /*?*/ | |
// Maybe.of(user2) | |
// .map(prop('details')) | |
// .map(prop('address')) | |
// .map(prop('city')) | |
// .orElse(1) /*?*/ | |
// const add = curry((a, b) => a + b) | |
// add(10, 2) /*?*/ | |
// Maybe.of(10).map(add) /*?*/ | |
// Maybe.of(10).map(add).ap(Maybe.of(10)) /*?*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment