Created
January 5, 2010 17:07
-
-
Save jed/269527 to your computer and use it in GitHub Desktop.
a function that dispatches to other functions based on signature
This file contains hidden or 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
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