Skip to content

Instantly share code, notes, and snippets.

@afshinm
Forked from arashmilani/gist:4732488
Last active December 12, 2015 06:59
Show Gist options
  • Save afshinm/4733756 to your computer and use it in GitHub Desktop.
Save afshinm/4733756 to your computer and use it in GitHub Desktop.
function assertType(obj, type) {
return obj.constructor.name === type.name
}
Object.prototype.assertType = function(type) {
return this.constructor.name === type.name
}
//Preparing test, mock objects
function Book(){};
function Desk(){};
var book = new Book();
//Bleh, you can't do 1.prototype() so I made an `one` variable
var one = 1;
/**
* With function
*/
assertType("test", String); //true
assertType(one, String); //false
assertType(one, Number); //true
assertType(book, Book); //true
assertType(book, Desk); //false
assertType([], Array); //true
assertType(function(){}, Function); //true
/**
* With prototype
*/
"test".assertType(String); //true
one.assertType(String); //false
one.assertType(Number); //true
book.assertType(Book); //true
book.assertType(Desk); //false
[].assertType(Array); //true
(function(){}).assertType(Function); //true
/**
* Tweet => code.
* jsPerf also available in: http://jsperf.com/asset-type
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment