2

I've set a function with variable arguments:

myfunc: (cmd, args...)->
    # cmd is a string
    # args is an array

And can be called like:

myfunc("one") # cmd = "one", args = undefined
myfunc("one","two") # cmd = "one", args = ["two"]
# etc...

Now, what if I want to call it with unknown number of arguments? Let's say I want to pass an array of args instead of arg1, arg2, arg3,.. how is that possible?

Trying myfunc("one",["two","three"]) or myfunc("one",someArgs) leads to the unfortunate:

# cmd = "one"
# args = [ ["two","three"] ];

Ideas?


P.S. I made it this to work by adding these ultra-simple lines in my function. But is there no other way?

if args? and args[0] instanceof Array
    args = args[0]

2 Answers 2

3

You don't need to manually use Function.prototype.apply for this. Splats can be used in an argument to list to build an array or in a function call to expand an array; from the fine manual:

Splats...

[...] CoffeeScript provides splats ..., both for function definition as well as invocation, making variable numbers of arguments a little bit more palatable.

awardMedals = (first, second, others...) ->
  #...

contenders = [
  #...
]

awardMedals contenders...

So you can say things like this:

f('one')

f('one', 'two')

f('one', ['two', 'three']...)
# same as f('one', 'two', 'three')

args = ['where', 'is', 'pancakes', 'house?']
f(args...)
# same as f('where', 'is', 'pancakes', 'house?')

and The Right Thing will happen.

Demo: http://jsfiddle.net/ambiguous/ztesehsj/

Sign up to request clarification or add additional context in comments.

Comments

1

Use Function.apply:

myfunc.apply @, [ "one", "two", "three" ]

Demo on CoffeeScript.org

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.