Rolando Garza El blog de rolandog

18Jan/070

type.of() – a more specific typeof()

The type.of ECMAScript (JavaScript) function is meant to be of help in identifying correctly the type of anything placed as an argument.

You can click the following link to see the code snippet in Snipplr.

var is={
        Null:function(a){
                return a===null;
        },
        Undefined:function(a){
                return a===undefined;
        },
        nt:function(a){
                return(a===null||a===undefined);
        },
        Function:function(a){
                return(typeof(a)==='function')?a.constructor.toString().match(/Function/)!==null:false;
        },
        String:function(a){
                return(typeof(a)==='string')?true:(typeof(a)==='object')?a.constructor.toString().match(/string/i)!==null:false;
        },
        Array:function(a){
                return(typeof(a)==='object')?a.constructor.toString().match(/array/i)!==null||a.length!==undefined:false;
        },
        Boolean:function(a){
                return(typeof(a)==='boolean')?true:(typeof(a)==='object')?a.constructor.toString().match(/boolean/i)!==null:false;
        },
        Date:function(a){
                return(typeof(a)==='date')?true:(typeof(a)==='object')?a.constructor.toString().match(/date/i)!==null:false;
        },
        HTML:function(a){
                return(typeof(a)==='object')?a.constructor.toString().match(/html/i)!==null:false;
        },
        Number:function(a){
                return(typeof(a)==='number')?true:(typeof(a)==='object')?a.constructor.toString().match(/Number/)!==null:false;
        },
        Object:function(a){
                return(typeof(a)==='object')?a.constructor.toString().match(/object/i)!==null:false;
        },
        RegExp:function(a){
                return(typeof(a)==='function')?a.constructor.toString().match(/regexp/i)!==null:false;
        }
};

var type={
        of:function(a){
                for(var i in is){
                        if(is[i](a)){
                                return i.toLowerCase();
                        }
                }
        }
};

I was inspired by reading an article in Planet PDF written by Kas Thomas'. The article is called Testing for Object Types in JavaScript.

About Rolando Garza

Rolando Garza is a Chemical Engineer that enjoys writing, programming, life, savate, playing basketball with his girlfriend and working as a Resin Engineer in ICASA.
Filed under: Posts Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.