T. Rex T. Rex - 11 months ago 50
CoffeeScript Question

Passing an Object to a function that accepts a param list

I have a function defined as follows

postEvent = (data) ->
throw new Error("category is required for structured events") if not category
throw new Error("action is required for structured events") if not action

$window.submit 'type1', data.category, data.action, data.label, data.property, data.value

category and action are required, but the remaining are not. If the
object doesn't contain a given value, it should not be passed.

I could use an absurd number of if statements, however I suspect there's a better way.
So I'm looking for a way to unwrap the objects values and pass to the other function.


data = {category: 'cat1', action: 'action1', value: 1.2}

this should result in the following

$window.submit 'type1', 'cat1', 'action1', 1.2

Answer Source

You can use destructuring:

postEvent = ({category, action, value}) ->
  console.log category, action, value

postEvent({ category: 'foo', value: 'bar' }) #logs foo, undefined, bar

Then you can use call to apply all the argument:

$window.sumbit.call $window, category, action, value

If you need validation, I recommend a different approach:

DATA_ORDERING = ['category', 'action', 'value']

postEvent = (data) ->
  let stuff = Object.keys data
    .sort (a, b) -> DATA_ORDERING.indexOf(a) - DATA_ORDERING.indexOf(b)
    .map (k) -> data[k]

  let valid = stuff.every (item) -> item? #make sure non-null

  if valid then $window.submit.apply $window, stuff