Skip to content

Instantly share code, notes, and snippets.

@amwmedia
Last active August 25, 2017 12:21
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 amwmedia/2c12b9f664b331b8c4d670048da50a9a to your computer and use it in GitHub Desktop.
Save amwmedia/2c12b9f664b331b8c4d670048da50a9a to your computer and use it in GitHub Desktop.
Glean... what you want from any data source.
/**
* glean - Access nested paths in an object whos structure we are uncertain of.
* Unholy marriage of Facebook's existential function and lodash get()
* https://facebook.github.io/react-native/blog/2017/03/13/idx-the-existential-function.html
* https://lodash.com/docs#get
*
* @param {Object} source the source object we are operating on
* @param {Function} accessor attepts to access the property desired
* @param {Any} defaultValue = null value to return if the accessor throws
* @return {Any}
*/
glean(source, accessor, defaultValue = null) {
try {
const val = accessor(source);
if (typeof val === 'undefined') { return defaultValue; }
return val;
} catch(err) {
return defaultValue;
}
}
@amwmedia
Copy link
Author

const src = {a: {b: 'c'}};

glean(src, _=>_.a.b);
// => "c"
glean(src, _=>_.a.b.c);
// => null
glean(src, _=>_.a.b.c, 'default');
// => "default"
glean(src, _=>_.a.b === true, false);
// => false
glean(src, _=>_.a.b === 'c', false);
// => true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment