I have a static javascript function that can take 1, 2 or 3 parameters:
function getData(id, parameters, callback) //parameters (associative array) and callb
Are you saying you can have calls like these: getData(id, parameters); getData(id, callback)?
In this case you can't obviously rely on position and you have to rely on analysing the type: getType() and then if necessary getTypeName()
Check if the parameter in question is an array or a function.
I recommend you to use ArgueJS.
You can just type your function this way:
function getData(){
arguments = __({id: String, parameters: [Object], callback: [Function]})
// and now access your arguments by arguments.id,
// arguments.parameters and arguments.callback
}
I considered by your examples that you want your id
parameter to be a string, right?
Now, getData
is requiring a String id
and is accepting the optionals Object parameters
and Function callback
. All the use cases you posted will work as expected.
I think you want to use typeof() here:
function f(id, parameters, callback) {
console.log(typeof(parameters)+" "+typeof(callback));
}
f("hi", {"a":"boo"}, f); //prints "object function"
f("hi", f, {"a":"boo"}); //prints "function object"
So use the typeof operator to determine if the second parameter is an Array or function.
This can give some suggestions: http://www.planetpdf.com/developer/article.asp?ContentID=testing_for_object_types_in_ja
I am not certain if this is work or homework, so I don't want to give you the answer at the moment, but the typeof will help you determine it.
You can use the arguments object property inside the function.
If your problem is only with function overloading (you need to check if 'parameters' parameter is 'parameters' and not 'callback'), i would recommend you don't bother about argument type and
use this approach. The idea is simple - use literal objects to combine your parameters:
function getData(id, opt){
var data = voodooMagic(id, opt.parameters);
if (opt.callback!=undefined)
opt.callback.call(data);
return data;
}
getData(5, {parameters: "1,2,3", callback:
function(){for (i=0;i<=1;i--)alert("FAIL!");}
});