Skip to content

Instantly share code, notes, and snippets.

@dnewcome
Last active July 24, 2017 22:00
Show Gist options
  • Save dnewcome/afa1edfee1ee083af458b51a0824be5e to your computer and use it in GitHub Desktop.
Save dnewcome/afa1edfee1ee083af458b51a0824be5e to your computer and use it in GitHub Desktop.
dependency-free get
// safely get object prop, like lodash get but without any dependencies
// specify path as dot delimited string
// optionally provide default value
function get(obj, path, def) {
path = path.split('.');
let ret = obj || {};
path.forEach((item) => {
ret = ret && ret[item];
});
return ret || def;
}
// tests
let get = require('./get');
let lang = get(process, 'env.LANG');
let blahblah = get(process, 'env.BLAHBLAH', 'icecream');
let blahblah2 = get(process, 'env.BLAHBLAH', 42);
let test1 = get(undefined, 'env.BLAHBLAH', 42);
let test2 = get(null, 'env.BLAHBLAH', 42);
console.log('lang should be en_US.UTF-8 ', lang, lang === 'en_US.UTF-8');
console.log('blahblah should use specified default of icecream ', blahblah, blahblah === 'icecream');
console.log('blahblah2 should use specified default of 42', blahblah2, blahblah2 === 42);
console.log('blahblah2 should use specified default of 42', blahblah2, blahblah2 === 42);
console.log('undefined object should use default value', test1, test1 === 42);
console.log('null object should use default value', test2, test2 === 42);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment