Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create two arrays in the same loop with CoffeeScript?

I want to create two arrays b and c at the same time. I know two methods which can be able to achieve it. The first method is

b = ([i, i * 2] for i in [0..10])
c = ([i, i * 3] for i in [0..10])

alert "b=#{b}"
alert "c=#{c}"

This method is very handy for creating only one array. I can not be the better way to get the better performance for computation.

The second method is

b = []
c = []
for i in [0..10]
  b.push [i, i*2]
  c.push [i, i*3]

alert "b=#{b}"
alert "c=#{c}"

This method seems good for computation efficiency but two lines b = [] c = [] have to be written first. I don't want to write this 2 lines but I have not find a good idea to have the answer. Without the initialization for the arrays of b and c, we can not use push method.

There exists the existential operator ? in Coffeescript but I don't know hot to use it in this problem. Do you have a better method for creating the arrays of b and c without the explicit initialization?

Thank you!

like image 475
yun_cn Avatar asked Mar 08 '13 08:03

yun_cn


1 Answers

You can use a little help from underscore (or any other lib that provides zip-like functionality):

[b, c] = _.zip ([[i, i * 2], [i, i * 3]] for i in [0..10])...

After executing it we have:

coffee> b 
[ [ 0, 0 ],
  [ 1, 2 ],
  [ 2, 4 ],
  [ 3, 6 ],
  [ 4, 8 ],
  [ 5, 10 ],
  [ 6, 12 ],
  [ 7, 14 ],
  [ 8, 16 ],
  [ 9, 18 ],
  [ 10, 20 ] ]

coffee> c
[ [ 0, 0 ],
  [ 1, 3 ],
  [ 2, 6 ],
  [ 3, 9 ],
  [ 4, 12 ],
  [ 5, 15 ],
  [ 6, 18 ],
  [ 7, 21 ],
  [ 8, 24 ],
  [ 9, 27 ],
  [ 10, 30 ] ]

See the section about splats in CoffeeScript docs for more details and examples.

like image 178
nl_0 Avatar answered Sep 29 '22 06:09

nl_0