public
Last active — forked from cowboy/overloading.js

Java-esque method overloading for JavaScript.

  • Download Gist
overloading.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
// Don't actually use this. Ever. Thx.
 
(function() {
 
var getClass = {}.toString, slice = [].slice, classNames = {
"[object Function]": "Function",
"[object Array]": "Array",
"[object String]": "String",
"[object Boolean]": "Boolean",
"[object Number]": "Number",
"[object Date]": "Date",
"[object RegExp]": "RegExp"
};
function getClassOf(value) {
var className;
if (value === null) {
return "Null";
} else if (value == null) {
return "Undefined";
}
className = getClass.call(value);
return classNames.hasOwnProperty(className) ? classNames[className] : "Object";
}
 
Function.overload = function(obj) {
return function() {
var signature = [], length = arguments.length;
while (length--) signature[length] = getClassOf(arguments[length]);
signature = signature.join(", ");
if (obj[signature]) {
return obj[signature].apply(this, arguments);
} else {
throw new Error('Signature "' + signature + '" not defined.');
}
};
};
}());
usage.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12
var func = Function.overload({
'Number, String': function(n, s) {
return 'The number ' + n + ' was passed, followed by string ' + s;
},
'String, Number': function(s, n) {
return 'The string ' + s + ' was passed, followed by number ' + n;
}
});
 
func(123, 'foo') // "The number 123 was passed, followed by string foo"
func('foo', 123) // "The string foo was passed, followed by number 123"
func(123, 456) // Error: Signature "number, number" not defined.

This is cool as hell. :clap:

Why isPropertyOf.call(classNames, className) instead of classNames.hasOwnProperty(className) ?

Also, this should probably handle Null and Undefined too :D

@cowboy isPropertyOf.call is an unfortunate habit acquired from using the toString, slice, and isPropertyOf boilerplate in nearly all my projects. :fish: Thanks for catching that; I've updated the code to support Null and Undefined as well.

You could also do:

if (value === null) {
  return "Null";
} else if (value == null) {
  return "Undefined";
}

@cowboy Sure. I thought typeof value == "undefined" would have been more readable, but value == null is far shorter.

That's what well-thought-out comments are for!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.