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 |
No, the .length of the last element function is 1.
@dherman I know, that actually why I wrote this, I was trying to illustrate why we need an API for testing if ...rest
is used. Here is related es discussion: https://mail.mozilla.org/pipermail/es-discuss/2012-June/023277.html
Oh I see I actually wrote in my comment that function length
will be 2
instead of 1
. I'm updating it now.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It would be intuitive to take advantage of ES.next
...rest
and write code like this:Which won't do what's user expects, since
length
of last element function will be1
.