osqlsa
Last Updated: February 25, 2016
·
1.31K
· emirotin
C2dfddeae5eb2b4cb24780d35c8c3f7f

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

Say Thanks
Respond