Skip to content

Instantly share code, notes, and snippets.

@keeto
Created June 27, 2010 06:49
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 keeto/454715 to your computer and use it in GitHub Desktop.
Save keeto/454715 to your computer and use it in GitHub Desktop.
Function.Typed: MultiMethod Helper
/*
Script: Function.Typed.js
Helper for multimethods.
Copyright and License:
Copyrighted 2010, Mark Obcena. MIT-Style License
Credits:
Inspired by "Multimethods in Python"
[http://alexgaynor.net/2010/jun/26/multimethods-python/]
*/
(function(){
var register = function(types, name, method){
if (method instanceof Function)
types[name.replace(/\s/g, '')] = method;
};
Function.Typed = function(methods){
var types = {};
var fn = function(){
var key = Array.prototype.slice.call(arguments).map(function(arg){
return typeOf(arg);
}).join(','), fn = types[key];
if (fn) return fn.apply(this, arguments);
else if (types['*']) return types['*'].apply(this, arguments);
else throw new TypeError('No method defined for type('+key+')');
}.extend({
register: function(name, method){
if (typeOf(name) == 'object'){
for (var key in name) register(types, key, name[key]);
return this;
}
register(types, name, method);
return this;
},
unregister: function(name){
delete types[name.replace(/\s/g, '')];
return this;
}
});
fn.register(methods);
return fn;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment