TestComplete: improving JScript typeof operator
@ Mo, 4 August 2008, 13:25JScript operator is used for getting type of the variable. There are six possible values that typeof returns: "number," "string," "boolean," "object," "function," and "undefined".
In this post we will improve typeof operator so that it can also return "date" and "array" values for corresponding data types.
There are a lot of date formats, but the most used among them are
mm/dd/yyyy, dd/mm/yyyy, m/d/yyyy, etc.
Year can be also represented by 2 digits, like this mm/dd/yy.
And several other characters can be used as a separator, like ".", "-", etc.
So we need to create a regular expression and check given value for matching this expression.
value.match(/\d{1,2}[\/.-]\d{1,2}[\/.-]\d{2,4}/)
In order to check whether given value is an array, we can try to use any array method for this value. If exception occurs, it means that this is not an array. We decided to use join method.
And here is an example of the function which can be used instead of typeof operator.
function _typeof(value)
{
switch(typeof(value))
{
case "string":
return (value.match(/\d{1,2}[\/.-]\d{1,2}[\/.-]\d{2,4}/) != null) ? "date" : "string";
break;
case "object":
try
{ value.join() }
catch(e)
{
if(e.number == -2146827850)
return "object"
else
throw e;
}
return "array";
break;
default:
return typeof(value);
}
}
