Created
June 27, 2010 06:49
-
-
Save keeto/454715 to your computer and use it in GitHub Desktop.
Function.Typed: MultiMethod Helper
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
/* | |
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