Skip to content

Instantly share code, notes, and snippets.

@lukesutton
Created April 20, 2010 01:58
Show Gist options
  • Save lukesutton/371925 to your computer and use it in GitHub Desktop.
Save lukesutton/371925 to your computer and use it in GitHub Desktop.
(function() {
var $f;
$f = function $f() {
var types = Array.prototype.slice.call(arguments);
var returnType;
function defineReturn(val) {
returnType = val;
return defineFn;
};
function defineFn(fn) {
var wrapper = function() {
checkPairs(types, arguments);
var returnValue = fn.apply(arguments);
if (returnType && !typeCheck(returnValue, returnType)) {
throw new Error("The return type of this function is incorrect.");
}
return returnValue;
}
wrapper.paramTypes = types;
wrapper.returnType = returnType;
wrapper.unwrapped = fn;
return wrapper;
};
return defineReturn;
};
function checkPairs(types, values) {
var l = types.length;
for (var i = 0; i < l; i++) {
if (!typeCheck(values[i], types[i])) {
throw new Error("Expected type not received.");
}
}
};
function typeCheck(obj, type) {
if (type === undefined || type === null) {
return obj === type;
}
else {
return obj.constructor === type;
}
};
this.$f = $f;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment