4

I have a function that should return all but the first argument

foo = -> arguments[1..]

foo(0,1,2,3,4)

unfortunately arguments is not an array but an object.

What is the best way to convert the object into an array?

3 Answers 3

10

There are a few CoffeeScript-ish options using a splat to take care of array-ifying arguments. You can use slice:

f = (args...) -> args.slice(1)

Demo

Or you could use a range instead of directly calling slice:

f = (args...) -> args[1..-1]

Demo

You can simplify the second version because:

Slices indices have useful defaults. An omitted first index defaults to zero and an omitted second index defaults to the size of the array.

So you could leave off the -1 and say just:

f = (args...) -> args[1..]

instead. Thanks to scar3tt for pointing this out.

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

4 Comments

@Wex: True but I think there's something to be said for the "I'm a variadic function" explicitness of (args...) that directly using arguments doesn't always give you.
interesting, the args... is essentially turned into [].slice.call(arguments) by the coffeescript compiler
CoffeeScript permits one or both indices in a range to be omitted (source). The args[1..-1] to me is a little needlessly confusing. My preference would be to use args[1..] instead. I do acknowledge that this may not have been the case at the time the answer was written.
@scarl3tt: I think I missed that. The only relevant thing I can find in the ChangeLog is "Both endpoints of a slice are now allowed to be omitted for consistency, effectively creating a shallow copy of the list." and that was from 1.3.1 on April 10, 2012 (i.e. about a year before this answer). Let me patch things up a bit.
1

You can ignore the first argument and use splats to capture the rest:

foo = (_, rest...) -> rest 

You could also do something like foo = (args...) -> args[1...], but that'll compile to two different calls to Array#slice (unlike the first snippet).

2 Comments

that is a great answer if I only want to ignore the rest of the arguments. I used the [1...] just to illustrate that I cannot do array operations...
@Michael_Scharf, ha, OK. Then yeah, the idiomatic way to treat arguments as an array in CoffeeScript is to simply declare the function as (args...) -> and then use args which is a real array.
0

What found is to use Array.prototype.slice:

coffee> foo = -> Array.prototype.slice.apply(arguments)[1..]
[Function]
coffee> foo(0,1,2,3,4)
[ 1, 2, 3, 4 ]

Another version would be

[].slice.call(arguments)

1 Comment

You could use :: instead of prototype: Array::slice.apply...

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.