Skip to content

Instantly share code, notes, and snippets.

@jimkang
Last active December 16, 2015 16:09
Show Gist options
  • Save jimkang/5461247 to your computer and use it in GitHub Desktop.
Save jimkang/5461247 to your computer and use it in GitHub Desktop.
A function that makes sure an options object has a certain set of expected properties. If properties are missing or of the wrong type, they are set to the default values defined in propInfoDict.
// propInfoDict should have prop names as the keys, then arrays
// as values that contain the expected type and the default value.
// options should be the options dictionary.
// Example:
// options = prepareOptions(options, {
// someDictionary: ['object', null],
// aFunction: ['function', function(datum) {
// return datum;
// }],
// message: ['string', 'OHAY GUYS'],
// count: ['number', 1000000]
// });
function prepareOptions(options, propInfoDict) {
if (!options) {
options = {};
}
for (var propName in propInfoDict) {
var valid = optionIsValid(options, propName,
propInfoDict[propName][0]);
if (!valid) {
options[propName] = propInfoDict[propName][1];
}
}
return options;
}
function optionIsValid(optionsDict, propName, expectedTypeName) {
var valid = false;
var value = optionsDict[propName];
if (typeof value === expectedTypeName) {
if (expectedTypeName === 'string') {
if (value.length) {
valid = true;
}
}
else {
valid = true;
}
}
return valid;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment