Created
April 22, 2012 23:54
-
-
Save ericelliott/2467606 to your computer and use it in GitHub Desktop.
Arguments / named params polymorph
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
/** | |
* The user can pass in the formal parameters, or a named | |
* parameters object in the first argument. Either way, | |
* we need to initialize the variables to the expected | |
* values. | |
* | |
* @param {String} optionNames Parameter names. | |
* | |
* @return {object} New configuration object. | |
*/ | |
getConfig = function getConfig(optionNames) { | |
var config = {}, // New config object | |
// Comma separated string to Array | |
optionNames = optionNames.split(','), | |
// Turn arguments into array, starting at index 1 | |
args = [].slice.call(arguments, 1); | |
optionNames.forEach(function (optionName, index) { | |
// Strip whitespace | |
optionName = optionName.trim(); | |
// Use first argument as params object if it exists... | |
config[optionName] = args[0][optionName] | |
|| args[index]; // or grab the formal parameter. | |
}); | |
return config; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This even allows you to mix and match both approaches, which I have found useful already.