Skip to content

Instantly share code, notes, and snippets.

@westc
Created December 26, 2014 22:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westc/da413cd2bab4053e9696 to your computer and use it in GitHub Desktop.
Save westc/da413cd2bab4053e9696 to your computer and use it in GitHub Desktop.
Parameterization of an object with the ability to set defaults.
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);
};
}
@westc
Copy link
Author

westc commented Dec 26, 2014

Let's define a function called random() which accepts min, max, and isInt. The min will default to 0 while max defaults to 1:

var random = param([['min', 0],['max', 1],'isInt'], function(min, max, isInt) {
  var ret = Math.random() * (max - min) + min;
  return isInt ? parseInt(ret) : ret;
});

It's as easy as that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment