Skip to content

Instantly share code, notes, and snippets.

@jeroenransijn
Last active December 11, 2015 09:19
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 jeroenransijn/4579206 to your computer and use it in GitHub Desktop.
Save jeroenransijn/4579206 to your computer and use it in GitHub Desktop.
function typed (types, cb) {
if (Object.prototype.toString.call(types) === '[object Array]' && typeof cb === "function") {
return function () {
var i = arguments.length, areTypesCorrect = true;
while (i--) {
// need to check for some literals: string/number/boolean
var type = typeof arguments[i], arg;
if (type === 'string') {
arg = new String();
} else if (type === 'number') {
arg = new Number();
} else if (type === 'boolean') {
arg = new Boolean();
} else {
arg = arguments[i];
}
if ( ! (arg instanceof types[i]) ) {
areTypesCorrect = false;
throw new TypeError('Argument '+ (i+1) + ' "' + arguments[i] + '" is not an instance of "' + types[i] + '" ');
break;
}
}
areTypesCorrect && cb.apply(this, arguments);
}
} else {
throw new TypeError('(typed): arguments given are not valid');
}
}
var myTypedFunction = typed([String, Array], function(str, arr) {
console.log(str, arr)
});
// will work
myTypedFunction('hello', ['world']);
// will not work
myTypedFunction(false, ['world']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment