Skip to content

Instantly share code, notes, and snippets.

Created September 20, 2014 08:20
Show Gist options
  • Save anonymous/befd711892fc613ffab7 to your computer and use it in GitHub Desktop.
Save anonymous/befd711892fc613ffab7 to your computer and use it in GitHub Desktop.
If a property chain exists, access it, else return undefined.
/*! maybe.js | v0.1.0 */
// If a property chain exists, access it, else return undefined.
//
// eg:
// var url = maybe(app, 'config.environment.buildURL', ['dev']);
var maybe = (function () {
// Different values for normal browser, strict mode, node.js, etc.
var defaultContext = this;
return function maybe(obj) {
var prevObj = defaultContext;
var nArgs = arguments.length;
var i = 0;
var prop = '';
var arg, tmp;
for (i = 1; i < nArgs; i += 1) {
arg = arguments[i];
if (typeof arg === 'string') {
arg = arg.split('.');
while ((prop = arg.shift()) !== undefined) {
if (obj instanceof Object && prop in obj) {
prevObj = obj;
obj = obj[prop];
} else {
return undefined;
}
}
} else if (Array.isArray(arg)) {
if (obj instanceof Function) {
tmp = obj.apply(prevObj, arg);
prevObj = obj;
obj = tmp;
} else {
return undefined;
}
} else {
throw Error('Invalid argument');
}
}
return obj;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment