Skip to content

Instantly share code, notes, and snippets.

@silverstrike
Last active December 14, 2015 15:29
Show Gist options
  • Save silverstrike/5108601 to your computer and use it in GitHub Desktop.
Save silverstrike/5108601 to your computer and use it in GitHub Desktop.
The following code is based on Angus Croll blog post "Fixing the JavaScript typeof operator" (http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator).
(function ( global, undefined ) {
"use strict";
var type = function ( objects, types, output ) {
var keyMap, result, testObjects, testTypes,
getType = function ( object ) {
if ( object && object.nodeType !== undefined ) {
return 'dom';
}
else if ( object === global ) {
return 'global';
}
else {
return ({}).toString.call( object )
.match( /\s([a-zA-Z]+)/ )[1].toLowerCase();
}
};
testObjects = getType( objects );
testTypes = getType( types );
if ( testTypes !== 'undefined' ) {
if ( testTypes === 'string' ) {
return testObjects === types;
}
else if ( testTypes === 'array' ) {
if ( output === 'array' ) {
return objects.map(function ( member, index ) {
return getType( member ) === types[index];
});
}
else if ( getType( output ) === 'string' ) {
result = {};
keyMap = output.split(/,\s?|\s+/);
objects.forEach(function ( member, index ) {
result[ keyMap[index] || member ] = {
'objectType': getType( member ),
'testFor': types[index],
'result': getType( member) === types[index]
};
});
return result;
}
else {
return objects.every(function ( member, index ) {
return getType( member ) === types[index];
});
}
}
}
return testObjects;
};
//Reveal to the global scope
Object.type = type;
}( this, undefined ));
(function ( global, undefined ) {
"use strict";
//Testing scenarios for the JSdot library
//type.js
var debug, objects = [null, 0, undefined, new Date(), new XMLHttpRequest(), (function () {}), {}, [], 'string'],
keys = 'nullify, none,,now getServer,,objective,stopArray,words',
matches = ['null', 'number', 'undefined', 'date', 'xmlhttprequest', 'function', 'object', 'array', 'string'],
misses = ['array', 'number', 'string', 'date', 'xmlhttprequest', 'function', 'object', 'number', 'string'];
debug = {
"objects array: ": objects,
"matches array: ": matches,
"misses array: ": misses,
"Object.type( {} )": Object.type( {} ),
"Object.type( 2013, 'number' )": Object.type( 2013, 'number' ),
"Object.type( objects, matches )": Object.type( objects, matches),
"Object.type( objects, misses )": Object.type( objects, misses ),
"Object.type( objects, matches, keys )": Object.type( objects, matches, keys ),
"Object.type( objects, matches, 'array' )": Object.type( objects, matches, 'array' ),
"Object.type( objects, misses, keys )": Object.type( objects, misses, keys ),
"Object.type( objects, misses, 'array' )": Object.type( objects, misses, 'array' )
};
Object.debug = debug;
}( this, undefined ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment