-
-
Save afshinm/4733756 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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