CoffeeScript: Generic pattern for arguments as array or as options object
Many libraries provide functions that accepts lots of arguments.
A standard solution to this is a single parameter that's options object.
subscribe = (options) ->
defaults =
async: false
options = _.extend {}, defaults, options
eventName = options.eventName
fn = options.fn
async = options.async
...
But often 95% of cases you need to pass 1 or 2 params (like event name and handler function) which is more readable in a normal way
subscribe = (eventName, fn) ->
Now a generic pattern for easily handling both cases with CoffeeScript
subscribe = () ->
if arguments.length == 1
{eventName, fn, async, whatEver} = arguments[0]
else
[eventName, fn, async, whatEver] = arguments
This uses destructuring assignment for objects and arrays: http://jashkenas.github.io/coffee-script/#destructuring
Written by Eugene Mirotin
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Coffeescript
Authors
iam4x
94.17K
ericdfields
63.02K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#