Last Updated: February 25, 2016
·
1.669K
· emirotin

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