Created
September 20, 2014 08:20
-
-
Save anonymous/befd711892fc613ffab7 to your computer and use it in GitHub Desktop.
If a property chain exists, access it, else return undefined.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! 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