Unordered function arguments in Javascript
Below is a regular function with named parameters:
function who(name, age, isMale, weight)
{
alert(name + ' (' + (isMale ? 'male' : 'female') + '), ' + age + ' years old, ' + weight + ' kg.');
}
who('Jack', 30, true, 90); //this is OK.
What I want to achive is; whether you pass the arguments in order or not; the function should produce a similar result (if not the same):
who('Jack', 30, true, 90); //should produce the same result with the regular function
who(30, 90, true, 'Jack'); //should produce the same result
who(true, 30, 'Jack', 90); //should produce the same result
This enables you to pass a list of arguments in any order but still will be开发者_开发百科 mapped to a logical order. My approach up to now is something like this:
function who()
{
var name = getStringInArgs(arguments, 0); //gets first string in arguments
var isMale = getBooleanInArgs(arguments, 0); //gets first boolean in arguments
var age = getNumberInArgs(arguments, 0); //gets first number in arguments
var weight = getNumberInArgs(arguments, 1); //gets second number in arguments
alert(name + ' (' + (isMale ? 'male' : 'female') + '), ' + age + ' years old, ' + weight + ' kg.');
}
There is a little problem here; functions such as getStringInArgs()
and getNumberInArgs()
go through all the arguments each time to find the arg by type at the specified position. I could iterate through args only once and keep flags for the positions but then I would have to do it inside the who() function.
Do you think this approach is logical and the only way? Is there a better way to do it?
EDIT 1: Code above actually works. I just want to know if there is a better way.
EDIT 2: You may wonder if this is necessary or whether it makes sense. The main reason is: I'm writing a jQuery function which adds a specific style to a DOM element. I want this function to treat its arguments like shorthand CSS values.
Example:
border: 1px solid red;
border: solid 1px red; /*will produce the same*/
So; here is the real and final code upto now:
(function($){
function getArgument(args, type, occurrence, defaultValue)
{
if (args.length == 0) return defaultValue;
var count = 0;
for(var i = 0; i < args.length; i++)
{
if (typeof args[i] === type)
{
if (count == occurrence) { return args[i]; }
else { count++; }
}
}
return defaultValue;
}
$.fn.shadow = function()
{
var blur = getArgument(arguments, 'number', 0, 3);
var hLength = getArgument(arguments, 'number', 1, 0);
var vLength = getArgument(arguments, 'number', 2, 0);
var color = getArgument(arguments, 'string', 0, '#000');
var inset = getArgument(arguments, 'boolean', 0, false);
var strInset = inset ? 'inset ' : '';
var sValue = strInset + hLength + 'px ' + vLength + 'px ' + blur + 'px ' + color;
var style = {
'-moz-box-shadow': sValue,
'-webkit-box-shadow': sValue,
'box-shadow': sValue
};
return this.each(function()
{
$(this).css(style);
});
}
})(jQuery);
Usage:
$('.dropShadow').shadow(true, 3, 3, 5, '#FF0000');
$('.dropShadow').shadow(3, 3, 5, '#FF0000', true);
$('.dropShadow').shadow();
I find using objects to be more straight-forward and less error prone in the future:
var person = {
name: 'Jack',
age: 30,
isMale: true,
weight: 90
};
who(person);
function who(person){
alert(person.name +
' (' + (person.isMale ? 'male' : 'female') + '), ' +
person.age + ' years old, ' +
person.weight + ' kg.');
}
That way when you come back years later you don't have to lookup to see if age was the first, second, or fifth number and is more descriptive of what you are trying to accomplish.
This seems unnecessarily complex, not just from the perspective of the function, which needs to reorder its arguments, but also from the perspective of whoever is calling. You say that the function can accept its paramters in any order, but that's not entirely true. Since your determination of which variable is which is based on type, it relies on each variable being a different type. The name and gender can be anywhere, but the numeric arguments have to be in a specific order. It also prevents someone from passing in "30" or "90", which are numbers but will be regarded as strings - confusing it with the name and not finding an age or weight.
You can cache the arguments of a specific type in the arguments array. This is a big hack, you could follow the same pattern with the other getTypeInArgs
function getNumberInArgs(args, index) {
if (!args.numbers) {
args.numbers = [];
for (var i=0; i < args.length; i++) {
// You have to implement isNumber
if ( isNumber (args[i]) ) {
args.numbers.push(args[i];
}
}
}
return args.numbers[index];
}
I've never heard of accepting arguments in any order, except for the implode function in PHP, and it's marked on its documentation page as a big hack for historical reasons. So I wouldn't do this. If the order is too confusing, I would use the approach of taking a literal object, as suggested by WSkid.
You could try copying the arguments array into something you can destructively update:
untested code: Edit: I think it works now.
function args_getter(their_arguments){
//copy arguments object into an actual array
//so we can use array methods on it:
var arr = Array.prototype.slice.call(their_arguments);
return function(type){
var arg;
for(var i=0; i<arr.length; i++){
arg = arr[i];
if(type == typeof arg){
arr.slice(i, 1);
return arg;
}
}
return "do some error handling here"
}
}
function foo(){
var args = args_getter(arguments);
var b1 = args('boolean');
var b2 = args('boolean');
var n1 = args('number');
console.log(n1, b1, b2);
}
//all of
// foo(1, true, false),
// foo(true, 1, false), and
// foo(true, false, 1)
// should print (1, true, false)
This is still O(N^2) since you go through the array every time. However this shouldn't be an issue unless your functions can receive hundreds of arguments.
I agree with Griffin. This cannot be done unless you limit the choices more than you have. As it is, you have a string, a boolean and two numbers. Without some more rules on what can be in what position, you cannot tell which number is which. If you're willing to make some rule about which number comes first or which number comes after some other argument, then you can sort it out. In general, I think this is a bad idea. It's much better (from the standpoint of good programming) to use an object like WSkid suggested.
Anyway, if you wanted to make a rule like the weight has to come after the age, then it could be done like this:
function findParm(args, type) {
for (var i = 0; i < args.length; i++) {
if (typeof args[i] == type) {
return(i);
}
}
return(-1);
}
function who(name, age, isMale, weight) {
// assumes all variables have been passed with the right type
// age is before weight, but others can be in any order
var _name, _age, _isMale, _weight, i;
var args = Array.prototype.slice.call(arguments);
_name = args[findParm(args, "string")]; // only string parameter
_isMale = args[findParm(args, "boolean")]; // only boolean parameter
i = findParm(args, "number"); // first number parameter
_age = args[i];
args.splice(i, 1); // get rid of first number
_weight = args[findParm(args, "number")]; // second number parameter
// you now have the properly ordered parameters in the four local variables
// _name, _age, _isMale, _weight
}
who("fred", 50, false, 100);
Working here in this fiddle: http://jsfiddle.net/jfriend00/GP9cW/.
What I would suggest is better programming is something like this:
function who(items) {
console.log(items.name);
console.log(items.age);
console.log(items.weight);
console.log(items.isMale);
}
who({name: "Ted", age: 52, weight: 100, isMale: true});
function who({name, age, isMale, weight})
{
alert(name + ' (' + (isMale ? 'male' : 'female') + '), ' + age + ' years old, ' + weight + ' kg.');
}
who({name:'Jack', age:30, isMale:true, weight90});
Taking parameters as an object, allows you to pass arguments in any order.
There is no way you can do this since you have arguments of the same type.
Unless age and weight have non-overlapping ranges, you can't do this. How are you supposed to distinguish between 30 and 60 for weight or age??
This code:
function who(items) { console.log(items.name); console.log(items.age); console.log(items.weight); console.log(items.isMale);}who({name: "Ted", age: 52, weight: 100, isMale: true});
That a previous posted sent seems sensible. But why make things complicated. My experience when people make things complicated things go wrong.
BTW - The solution above (as the previous posted gave) is similar to the Perl solution.
精彩评论