MultiFn is a JavaScript utility which allows multiple implementations of a function based on different arguments. i.e. if you want different code to run if a function is called with an Array as opposed to an Object.
MultiFn.js was authored by Liam Goodacre using Coffee-Script.
Check out the "[src/out]/test/" folders for example(s).
CoffeeScript:
myFn = new MultiFn { "Number Number": (_n1, _n2) -> myFn(_n1) + myFn(_n2) "Number": (_num) -> _num "String": (_str) -> parseInt(_str, 10) }JavaScript:
var myFn = new MultiFn({ "Number Number": function (_n1, _n2) { return myFn(_n1) + myFn(_n2); }, "Number": function (_num) { return _num; }, "String": function (_str) { return parseInt(_str, 10); } });
MultiFn supports having a default implementation function, should none of the argument patterns match. The syntax is as follows:
CoffeeScript:
someFn = new MultiFn { #...other functions... "default": -> # some default implementation #...other functions... }
JavaScript:
var someFn = new MultiFn({ //...other functions... "default": function () { // some default implementation }, //...other functions... });
The string of types identifying the arguments for an implementation, is a space delimited sequence of regular expressions.
This means that instead of writing "Number", you could write "^Num", or event just "^N". It also means you can do things like "Element$" which would match "HTMLElement", "HTMLBodyElement", etc...
Another adavantage to this, is that ".*" will match any type of value:
"Number .* Number": (_num1, _anything, _num2) -> #...