Created
November 12, 2013 08:45
-
-
Save OlavHN/7427620 to your computer and use it in GitHub Desktop.
Type checking in javascript!
This file contains 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 type_checker() { | |
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; | |
function getParamNames(func) { | |
var fnStr = func.toString().replace(STRIP_COMMENTS, ''); | |
var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(/([^\s,]+)/g); | |
if(result === null) | |
result = []; | |
return result; | |
} | |
return function(types, func) { | |
var args = getParamNames(func); | |
return function() { | |
var funcArgs = arguments; | |
args.forEach(function(arg, i) { | |
if (types[arg] !== funcArgs[i].constructor.name) | |
throw 't TypeError ' + arg + ' expected ' + types[arg] + ' was ' + funcArgs[i].constructor.name | |
}); | |
func.apply(this, arguments); | |
} | |
} | |
} | |
var t = type_checker(); | |
// Example | |
t({name: 'String', age: 'Number'}, | |
function greeting(name, age) { | |
console.log('Hello ' + name + '. You\'re ' + age + ' years old'); | |
}); | |
function Cat() {} | |
Cat.prototype.hello = "Meow"; | |
var greet = t({cat: 'Cat'}, | |
function(cat) { | |
console.log(cat.hello); | |
}); | |
greet(new Cat()); // Meow | |
greet({hello: "Barf"}); // Throw: "t TypeError cat expected Cat was Object" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice :)