Skip to content

Instantly share code, notes, and snippets.

@XoseLluis
Last active December 16, 2015 01:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XoseLluis/5353501 to your computer and use it in GitHub Desktop.
Save XoseLluis/5353501 to your computer and use it in GitHub Desktop.
Decorates a given JavaScript function with checking/assignment of default values to undefined parameters
//decorates a given function with checking/assignment of default values to undefined parameters
function decorateWithDefaultsChecking(targetFunc /* ,default1, default2... */){
var defaults = [].slice.call(arguments, 1)
if (!defaults)
return targetFunc;
var opStart = targetFunc.length - defaults.length;
return function(){
for(i=0; i<defaults.length; i++){
if (arguments[opStart + i] === undefined){
arguments[opStart + i] = defaults[i];
}
}
//the next line below here is essential, remember that arguments is not a real array, but an "array like" object,
//so in order for this to work we need to set the length propety on our own, otherwise, the new assigned values are ignored when invoking apply
arguments.length = arguments.length + defaults.length;
return targetFunc.apply(this, arguments);
};
}
function formatWords(word1, word2, op1, op2, op3){
return op1 + word1 + op2 + word2 + op3;
}
console.log("before decoration");
console.log(formatWords("Asturies", "Xixon"));
var defaultsAware = decorateWithDefaultsChecking(formatWords, "->", ":", ".");
console.log("after decoration");
console.log(defaultsAware("Asturies", "Xixon"));
console.log(defaultsAware("Asturies", "Xixon", "+"));
console.log(defaultsAware("Asturies", "Xixon", "+", ";"));
console.log(defaultsAware("Asturies", "Xixon", "[", ",", "]"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment