Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert arguments to an array in coffeescript?

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?

like image 324
Michael_Scharf Avatar asked Dec 20 '22 02:12

Michael_Scharf


1 Answers

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.

like image 102
mu is too short Avatar answered Feb 23 '23 19:02

mu is too short