Coffee- script cycle efficiency

super simple coffeescript question

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

It works. But I know that with syntactic candy, there is probably also a more coffeescriptish way to write this. Is there any way to write this without using i?

+3
source share
4 answers

The canonical way of CoffeeScript is to use it for understanding which will return an array:

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

Or, in one line:

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

See Loops and Tips :

Note that since we assign the meaning of the concepts to a variable in the above example, CoffeeScript collects the result of each iteration into an array.

+3
source
circles.push(new MakeCircle(cnBlue, coordinate.x, coordinate.y, 16, 8, 0, theCanvas.ctx))

;)

+1
source

"coffeescriptish" :

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

i 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
0

jQuery:

circles = jQuery.map(coordinates, 
    (coordinate) -> new MakeCircle(cnBlue, coordinate.x, coordinate.y, 16, 8, 0, theCanvas.ctx)
)

I have never written CoffeeScript before, so I apologize if this does not compile as is. This is certainly a more “functional” style, capable of doing what you want, which I identify with modern javascript.

-1
source

All Articles