Skip to content

Instantly share code, notes, and snippets.

@Gozala
Created June 11, 2012 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gozala/2911817 to your computer and use it in GitHub Desktop.
Save Gozala/2911817 to your computer and use it in GitHub Desktop.
arity based dispatch
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
}
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
@Gozala
Copy link
Author

Gozala commented Jun 11, 2012

It would be intuitive to take advantage of ES.next ...rest and write code like this:

var sum2= dispatcher([
  function() { return 0 },
  function(x) { return x },
  function(x, y) { return x + y },
  function(x, ...rest) { return rest.reduce(function(x, y) { return x + y }) }
])

sum2(2, 3, 4)     // =>  Error: Exception: Arity is not supported

Which won't do what's user expects, since length of last element function will be 1.

@dherman
Copy link

dherman commented Jun 15, 2012

No, the .length of the last element function is 1.

@Gozala
Copy link
Author

Gozala commented Jun 15, 2012

@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

@Gozala
Copy link
Author

Gozala commented Jun 15, 2012

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