Created
June 1, 2016 19:57
-
-
Save willgm/9be4272aa60aba0de2dcba850bfc0188 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
var person = { | |
name: 'Homer Simpson', | |
address: { | |
street: '123 Fake St.', | |
city: 'Springfield' | |
} | |
}; | |
//Complete Imperative | |
if (person != null && person['address'] != null) { | |
var state = person['address']['state']; | |
if (state != null) { | |
console.log(state); | |
} | |
else { | |
console.log('State unknown'); | |
} | |
} | |
//Imperative with Functional features | |
var state = person && person['address'] && person['address']['state']; | |
console.log(state || 'State unknown'); | |
//Functional direct | |
console.log(_.get(person, 'address.state', 'State unknown')); | |
//Functional comonad | |
console.log( | |
_.chain(person) | |
.result('address') | |
.result('state', 'State unknown') | |
.value() | |
); | |
//Functional monad | |
console.log( | |
Maybe(person) | |
.bind(p => p['address']) | |
.bind(a => p['state']) | |
.maybe('State unknown', s => s) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment