Created
December 26, 2014 22:37
-
-
Save westc/da413cd2bab4053e9696 to your computer and use it in GitHub Desktop.
Parameterization of an object with the ability to set defaults.
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 param(arrFields, callback) { | |
for (var t, o = {}, defaults = [], len = arrFields.length, i = len; i--;) { | |
t = o.toString.call(t = arrFields[i]) == '[object Array]' ? t : [t]; | |
defaults[i] = t[1]; | |
arrFields[i] = t[0]; | |
} | |
return function(fields) { | |
for (var t, args = arrFields.slice.call(arguments, 0), i = len; i--;) { | |
args.unshift(fields && (o.hasOwnProperty.call(fields, t=arrFields[i]) ? fields[t] : defaults[i])); | |
} | |
return callback.apply(this, args); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Let's define a function called
random()
which acceptsmin
,max
, andisInt
. Themin
will default to0
whilemax
defaults to1
:It's as easy as that.