Skip to content

Instantly share code, notes, and snippets.

@ChetHarrison
Created September 16, 2015 19:44
Show Gist options
  • Save ChetHarrison/d1af7cc0cee3cebb0c63 to your computer and use it in GitHub Desktop.
Save ChetHarrison/d1af7cc0cee3cebb0c63 to your computer and use it in GitHub Desktop.
Maybe Modad Example
'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 ) ) );
// 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