Skip to content

Instantly share code, notes, and snippets.

@arian
Created April 17, 2011 14:09
Show Gist options
  • Save arian/924057 to your computer and use it in GitHub Desktop.
Save arian/924057 to your computer and use it in GitHub Desktop.
Overload functions or methods by the types of the arguments
// Simple use
var fn = Function.overload([
['string', 'number', function(name, age){
return name + ' is ' + age + ' years old';
}],
[String, function(name){
return 'it is just ' + name;
}]
]);
console.log(fn('arian'));
console.log(fn('arian', 20));
console.log(fn(34));
// it is just arian
// arian is 20 years old
// null
// Using with Class
var Person = new Class({
initialize: Function.overload([
['string', 'string', function(first, last){
this.first = first;
this.last = last;
console.log('first: ' + first +' and last: ' + last);
}],
['string', Number, function(last, age){
this.last = last;
this.age = age;
console.log('Just the last name: ' + last + ' and you are ' + age + ' years old');
}],
function(){
// throw Error('pass at least your last name');
}
])
});
new Person('Arian', 'Stolwijk');
new Person('Stolwijk', 20);
new Person();
// first: Arian and last: Stolwijk
// Just the last name: Stolwijk and you are 20 years old
// Uncaught TypeError: pass at least your last name
Function.overload = function(fns, thisArg){
var dflt = (typeOf(fns[fns.length - 1]) == 'function') ? fns.pop() : null;
return function(){
var args = Array.from(arguments),
self = thisArg || this;
overload: for (var i = 0, l = fns.length; i < l; i++){
var types = fns[i].slice(0, -1), length = types.length,
fn = fns[i][length];
if (length != args.length) continue;
for (var j = length; j--;){
if (
!(instanceOf(types[j], Type) && instanceOf(args[j], types[j]))
&& typeOf(args[j]) != types[j]
) continue overload;
}
return fn.apply(self, args);
}
return dflt && dflt.apply(self, args);
};
};
@fat
Copy link

fat commented Apr 18, 2011

this is really cool

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