Last active
March 19, 2019 20:40
-
-
Save corycook/356ae8cf0879ae906c01 to your computer and use it in GitHub Desktop.
JavaScript function type checking and overloading
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 create() { | |
var types = Array.prototype.slice.call(arguments, 0, arguments.length - 1); | |
var body = arguments[arguments.length - 1]; | |
return function () { | |
if (arguments.length < types.length) | |
throw new Error("Argument count mismatch."); | |
for (var i = 0; i < types.length; i++) { | |
if (arguments[i].constructor != types[i] && !(arguments[i] instanceof types[i])) | |
throw new Error("Argument type mismatch. (" + types[i].name + ")"); | |
} | |
return body.apply(this, arguments); | |
} | |
} | |
function overload(a) { | |
if (arguments.length == 1) return a; | |
var c = overload.apply(this, Array.prototype.slice.call(arguments, 1)); | |
return function () { | |
try { | |
return a.apply(this, arguments); | |
} catch (e) { | |
return c.apply(this, arguments); | |
} | |
} | |
} | |
var f_string = create(String, function(s) { | |
console.log("String: " + s); | |
}); | |
var f_number = create(Number, function(n) { | |
console.log("Number: " + n); | |
}); | |
var f_bool_string = create(Boolean, String, function(b, s) { | |
console.log("Boolean: " + b + ", String: " + s); | |
}); | |
var f = overload(f_string, f_number, f_bool_string); | |
f(2.1); // logs "Number: 2.1" | |
f(true, "Testing"); // logs "Boolean: true, String: Testing" | |
f("Test"); // logs "String: Test" | |
f(true); // throws Error; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment