Created
June 11, 2012 18:38
-
-
Save Gozala/2911817 to your computer and use it in GitHub Desktop.
arity based dispatch
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
function dispatcher(methods, fallback) { | |
function dispatch() { | |
var method = dispatch.methods[arguments.length] || fallback | |
if (typeof(method) !== 'function') | |
throw Error('Arity is not supported') | |
return method.apply(this, arguments) | |
} | |
dispatch.methods = methods.reduce(function(methods, method) { | |
methods[method.length] = method | |
return methods | |
}, []) | |
return dispatch | |
} |
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
var sum = dispatcher([ | |
function() { return 0 }, | |
function(x) { return x }, | |
function(x, y) { return x + y } | |
], function(x, y, z) { | |
return Array.prototype.slice.call(arguments, 1).reduce(function(x, y) { | |
return sum(x, y) | |
}, x) | |
}) | |
sum() // => 0 | |
sum(2) // => 2 | |
sum(2, 3) // => 5 | |
sum(2, 3, 4) // => 9 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Oh I see I actually wrote in my comment that function
length
will be2
instead of1
. I'm updating it now.