Last active
December 16, 2015 01:09
-
-
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
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
//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); | |
}; | |
} |
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
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