I have been seeing functions with signatures
some_fn arg1, arg2, [optional], cb
How is this done?
I have been seeing functions with signatures
some_fn arg1, arg2, [optional], cb
How is this done?
jQuery does that sort of thing all the time, on for example:
.on( events [, selector ] [, data ], handler(eventObject) )
The way it works is that the inner optional arguments and the final argument have different types so the function can parse arguments by hand using typeof (or similar but looser checks like the various is* functions in Underscore) to figure out how it was called. If there are multiple things in the possible argument list that are the same type then you'd throw a length check into the mix to try and figure out what the intent is.
For example:
f = () ->
args = Array::slice.apply(arguments)
if(typeof args[0] == 'function')
args[0]()
else
console.log("#{args[0]} is not a function")
f(1, 2, 3)
f(-> console.log('pancakes'))
Demo: http://jsfiddle.net/ambiguous/c6UwC/
A more CoffeeScript-ish version would use ... instead of dealing with arguments directly:
f = (args...) ->
if(typeof args[0] == 'function')
args[0]()
else
console.log("#{args[0]} is not a function")
setTimeout and setInterval do it but those signatures are (IMO) mistakes and lead to lots of nasty looking code).