yun_cn
yun_cn

Reputation: 83

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!

Upvotes: 7

Views: 359

Answers (2)

nl_0
nl_0

Reputation: 391

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.

Upvotes: 4

Sanketh Katta
Sanketh Katta

Reputation: 6311

How about this using the existential operator:

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

console.log "b=#{b}"
console.log "c=#{c}"

Or to be a bit more understandable:

for i in [0..10]
    (if b? then b else b = []).push [i, i*2]
    (if c? then c else c = []).push [i, i*3]

console.log "b=#{b}"
console.log "c=#{c}"

EDIT: from comments:

OK but you you have to write so many tedious codes. The same reason is also for ` (b = b or []).push [i, i*2]

It is tedious, so we can wrap it in a function (but beware the variables will be global now):

# for node.js
array = (name) -> global[name] = global[name] or []

# for the browser
array = (name) -> window[name] = window[name] or []

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

console.log "b=#{b}"
console.log "c=#{c}"

Upvotes: 1

Related Questions