Skip to content

Instantly share code, notes, and snippets.

@amwmedia
Last active Aug 25, 2017
Embed
What would you like to do?
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