Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting every two elements from an array in CoffeeScript

Tags:

coffeescript

I want to use every pair of entries in an array. Is there an effective way to do this in CoffeeScript without using the length property of the array?

I am currently doing something like the following:

# arr is an array
for i in [0...arr.length]
    first = arr[i]
    second = arr[++i]
like image 436
knpwrs Avatar asked Jul 09 '12 02:07

knpwrs


1 Answers

CoffeeScript has for ... by for adjusting the step size of a normal for loop. So iterate over the array in steps of 2 and grab your elements using an index:

a = [ 1, 2, 3, 4 ]
for e, i in a by 2
    first  = a[i]
    second = a[i + 1]
    # Do interesting things here

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

If you want, you could use a destructured assignment combined with an array slice inside the loop:

a = [ 'a', 'b', 'c', 'd' ]
for e, i in a by 2
    [first, second] = a[i .. i + 1]
    #...

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

You could also skip the ignored variable and use a range loop:

# three dots, not two
for i in [0 ... a.length] by 2
    [first, second] = a[i .. i + 1]
    #...

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

That compiles to a for(i = 0; i < a.length; i += 2) loop like all the rest do so the range doesn't cost you anything.​

like image 174
mu is too short Avatar answered Jan 02 '23 21:01

mu is too short