Reputation: 7144
I'm making up a way of setting function array parameter to a default value (one ES5 not new ES6/2015).
My first idea was this:
window.fnc = function(args){
defaults = {
height: 120,
width: 32
}
args = args || defaults;
console.log(args['height']+'x'+args['width'])
}
and will be used like this:
fnc({height:45, width:12}); //Result: 45x12
or
fnc(); //Result: 120x32
This works ok. But of course at line #7 the args is replaced by defaults or it is not, so if either one of the 2 values are missing i get an undefined
.
fnc({height:45}); //Result: 45xundefined
How do I go about this?
Upvotes: 1
Views: 95
Reputation: 2569
You can iterate the keys of default to copy the one missing in args.
window.fnc = function(args){
defaults = {
height: 120,
width: 32
}
//args = args || defaults;
if(args == null)
args = defaults;
else {
for(var i in defaults) {
if(args[i] == null) args[i] = defaults[i];
}
}
console.log(args['height']+'x'+args['width'])
}
If you have sub-objects in defaults
, you will need to do a recursive function.
EDIT:
Recursive example:
// check if obj is an object
function isObject(obj) {
return typeof obj == "object";
}
// check if obj is an array
function isArray(obj) {
return (typeof obj == "object") && (Object.getPrototypeOf( obj ) === Array.prototype);
}
// copy the attributes from original into dest
function copy_attributes(original, dest) {
for(var i in original) {
if(isArray(original[i])) {
dest[i] = JSON.parse(JSON.stringify(original[i])); // copy
}
else if(isObject(original[i])) {
copy_attributes(original[i], dest[i]);
}
else {
dest[i] = JSON.parse(JSON.stringify(original[i])); // copy
}
}
};
Upvotes: 2
Reputation: 2602
I use this code snippet from time to time:
args = args || defaults;
for (var opt in defaults) {
if (defaults.hasOwnProperty(opt) && !args.hasOwnProperty(opt)) {
args[opt] = defaults[opt];
}
}
Basically you iterate over all the values from the default arguments (for (var opt...
) and check against the values of the arguments whether it is missing or not. (if (defaults.has...
). If it is missing, add the default value (args[opt] =...
).
(I think I even found this snippet on SA, but not sure. Will add a link to the original answer if so.)
Upvotes: 3