Skip to content

Instantly share code, notes, and snippets.

@OlavHN
Created November 12, 2013 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OlavHN/7427620 to your computer and use it in GitHub Desktop.
Save OlavHN/7427620 to your computer and use it in GitHub Desktop.
Type checking in javascript!
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"
@sergi
Copy link

sergi commented Nov 13, 2013

Nice :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment