Skip to content

Instantly share code, notes, and snippets.

@jed
Created Jan 5, 2010
Embed
What would you like to do?
a function that dispatches to other functions based on signature
function Dispatcher() {
var signatures = [], functions = [];
function fn() {
var
args = arguments,
argNo,
arity = args.length,
sigs = signatures[ arity ],
sigNo = sigs ? sigs.length : 0,
match = fn.noMatch;
eachSig: while ( sigNo-- ) {
argNo = arity;
while ( argNo-- )
if ( sigs[ sigNo ][ argNo ]( args[ argNo ] ) !== true )
continue eachSig;
match = functions[ arity ][ sigNo ];
break;
}
return match.apply( this, args );
};
fn.add = function( args, target ) {
var arity = args.length;
if ( !signatures[ arity ] ) {
signatures[ arity ] = [];
functions[ arity ] = [];
}
signatures[ arity ].push( args );
functions[ arity ].push( target );
return fn;
};
fn.noMatch = function() { throw "Argument signature not supported." };
return fn;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment