Skip to content

Instantly share code, notes, and snippets.

@lukesutton
Created March 29, 2010 23:23
Show Gist options
  • Save lukesutton/348543 to your computer and use it in GitHub Desktop.
Save lukesutton/348543 to your computer and use it in GitHub Desktop.
function typeCheck(obj, type) {
if (type === undefined || type === null) {
return obj === type;
}
else {
return obj.constructor === type;
}
}
function check() {
if ((arguments.length % 2) !== 0) {
throw new Error("Too few arguments specified; checks must be passed in pairs.");
}
var l = arguments.length / 2, i = 1, o = 0;
do {
if (!typeCheck(arguments[o], arguments[o + 1])) {
throw new Error("Type does no match, noooooo!");
}
o += 2;
i += 1;
} while (i <= l);
}
function getType(obj) {
if (obj === undefined) {
return undefined;
}
else if (obj === null) {
return null;
}
else {
switch(Object.prototype.toString.apply(obj)) {
case '[object Array]': return Array; break;
case '[object Date]': return Date; break;
case '[object RegExp]': return RegExp; break;
case '[object Function]': return Function; break;
case '[object Number]': return Number; break;
case '[object String]': return String; break;
default: return Object; break;
}
}
}
function typeCheck(obj, type) {
if (type === undefined || type === null) {
return obj === type;
}
else {
return obj.constructor === type;
}
}
function quickTest() {
console.log("Function: ", typeCheck(function(){}, Function));
console.log("String: ", typeCheck('blah', String));
console.log("Number: ", typeCheck(1, Number));
console.log("Object: ", typeCheck({}, Object));
console.log("Array: ", typeCheck([], Array));
console.log("Date: ", typeCheck(new Date(), Date));
console.log("RegExp: ", typeCheck(/\w+/, RegExp));
console.log("undefined: ", typeCheck(undefined, undefined));
console.log("null: ", typeCheck(null, null));
// Check a custom type
var Person = function() {};
var p = new Person()
console.log("Person: ", typeCheck(p, Person));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment