Hi everyone! I’m write the check of arguments data types inside function body. But I want to create the common function for check of data types, which will be used in several other functions.
It’s my constructor of “Cat” object:
function Cat(name, age, owner) {
if (!checkArgsDataTypes(arguments.callee, ["string", "number", "Man"])) {
throw new Error("Incorrect data type of arguments");
}
/* Continue function body if data types is correct */
}
Here creating of the “Cat” object:
var my_cat = new Cat("Tom", 2, new Man());
And this my variant of the common check-function:
function checkArgsDataTypes(func_link, types_array) {
var i;
var current_data_type;
if (typeof func_link != "function") {
throw new Error("the first argument must be a function");
}
if (types_array instanceof Array) {
if (func_link.arguments.length != types_array.length) {
throw new Error("not matching count of arguments and count of array-type items");
}
if (types_array.length > 0) {
for (i = 0; i < types_array.length; i ++) {
if (typeof types_array[i] != "string") {
throw new Error("types_array items must have string data type");
}
}
}
else {
throw new Error("Types array is empty");
}
for (i = 0; i < types_array.length; i ++) {
current_data_type = types_array[i].toLowerCase();
/* check simple data types */
if (current_data_type == "string" || current_data_type == "object" || current_data_type == "number") {
if (typeof func_link.arguments[i] != current_data_type) {
return false;
}
}
/* check complex data types */
else {
if (func_link.arguments[i].constructor.name != types_array[i]) {
return false;
}
}
}
return true;
}
else {
throw new Error("the second argument must be an array");
}
}
I wanna know, what is more less and simply variant of the common function for check data types?
What are your suggestions? Thanks.