Skip to content

Instantly share code, notes, and snippets.

@willgm
Created June 1, 2016 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willgm/9be4272aa60aba0de2dcba850bfc0188 to your computer and use it in GitHub Desktop.
Save willgm/9be4272aa60aba0de2dcba850bfc0188 to your computer and use it in GitHub Desktop.
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