Created
September 16, 2015 19:44
-
-
Save ChetHarrison/d1af7cc0cee3cebb0c63 to your computer and use it in GitHub Desktop.
Maybe Modad Example
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
'use strict'; | |
import Maybe from 'maybe'; | |
import R from 'ramda'; | |
var person = { | |
'name' : 'Homer Simpson', | |
'address' : { | |
'street' : '123 Fake St.', | |
'city' : 'Springfield' | |
}, | |
age : 20 | |
}; | |
const state = x => x.state; | |
const address = x => x.address; | |
const toUpper = ''.toUpperCase; | |
const toLower = ''.toLowerCase; | |
const concat = [].concat; | |
const age = x => x.age; | |
const personsState = Maybe.of( person ) | |
.map( address ) | |
.map( state ) | |
.map( toUpper ) | |
.map( toLower ); | |
console.log( personsState ); | |
const newAge = Maybe.of( person ) | |
.map( age ) | |
.map( R.add( 5 ) ) | |
.map( R.multiply( 10 ) ); | |
console.log( newAge ); | |
const anotherWay = R.map( R.compose( R.add( 5 ), age ) ); | |
console.log( anotherWay( Maybe.of( person ) ) ); |
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
// from https://github.com/MostlyAdequate/mostly-adequate-guide/blob/master/ch8.md | |
'use strict'; | |
const Maybe = function( x ) { | |
this.__value = x; | |
}; | |
Maybe.of = function( x ) { | |
return new Maybe( x ); | |
}; | |
Maybe.prototype.isNothing = function() { | |
return ( this.__value === null || this.__value === undefined ); | |
}; | |
Maybe.prototype.map = function( f ) { | |
return this.isNothing() ? Maybe.of( null ) : Maybe.of( f( this.__value ) ); | |
}; | |
export default Maybe; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment