Reputation: 30015
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
?
Upvotes: 3
Views: 296
Reputation: 39223
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)
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.
Upvotes: 4
Reputation: 19581
More "coffeescriptish" is writing it on one line :
circles = []
circles[i] = new MakeCircle(cnBlue, coor.x, coor.y, 16, 8, 0, theCanvas.ctx) for coor, i in coordinates
you could remove i
when using push
circles = []
mc = (x,y) -> new MakeCircle cnBlue,x,y,16,8,0,theCanvas.ctx
circles.push mc(coor.x,coor.y) for coor in coordinates
Upvotes: 1
Reputation: 13104
You can always use jQuery map:
circles = jQuery.map(coordinates,
(coordinate) -> new MakeCircle(cnBlue, coordinate.x, coordinate.y, 16, 8, 0, theCanvas.ctx)
)
I've never actually written CoffeeScript before, so apologies if that doesn't compile as is. This is definately a more "functional" style way of doing what you want, which I identify with modern javascript.
Upvotes: 0
Reputation: 12265
circles.push(new MakeCircle(cnBlue, coordinate.x, coordinate.y, 16, 8, 0, theCanvas.ctx))
;)
Upvotes: 2