Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

coffee-script loop efficiency

Tags:

coffeescript

super simple coffeescript question

circles = []
for coordinate, i in coordinates
    circles[i] = new MakeCircle(cnBlue, coordinate.x, coordinate.y, 16, 8, 0, theCanvas.ctx) 

This works. But I know that with the syntax candy there is probably and even more coffeescriptish way to write this. Is there a way to write this without using the i?

like image 728
Fresheyeball Avatar asked Aug 16 '26 06:08

Fresheyeball


1 Answers

The canonical CoffeeScript way is to use a for comprehension, which will return an array:

circles = for coordinate in coordinates
  new MakeCircle(cnBlue, coordinate.x, coordinate.y, 16, 8, 0, theCanvas.ctx)

Or, on one line:

circles = (new MakeCircle(cnBlue, coordinate.x, coordinate.y, 16, 8, 0, theCanvas.ctx) for coordinate in coordinates)

See Loops and Comprehensions:

Note how because we are assigning the value of the comprehensions to a variable in the example above, CoffeeScript is collecting the result of each iteration into an array.

like image 111
Linus Thiel Avatar answered Aug 24 '26 06:08

Linus Thiel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!