Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoffeeScript 2 Dimensional Array Usage

Tags:

coffeescript

I feel like I'm missing something with CoffeeScript and 2 dimensional arrays. I'm simply attempting to make a grid of spaces (think checkers). After some searching and a discovery with the arrays.map function, I came up with this:

@spaces = [0...20].map (x)->
  [0...20].map (y) ->
    new Elements.Space()

And this seems to work great, I have a nice 2 dimensional array with my Space object created in each. But now I want to send the created space constructor the x,y location. Because I'm two layers deep, I lost the x variable when I entered the map function for y.

Ideally I would want to do something like:

@spaces = [0...20].map (x)->
  [0...20].map (y) ->
    new Elements.Space(x, y)

or something that feels more natural to me like:

for row in rows
  for column in row
    @spaces[row][column] = new Elements.Space(row, column)

I'm really open to any better way of doing this. I know how I would do it in standard JavaScript, but really would like to learn how to do it in CoffeeScript.

like image 293
Chris Avatar asked Sep 21 '26 10:09

Chris


1 Answers

Your first attempt with map is a valid way to do it. You don't actually lose x, because closures. So there's nothing wrong with your second code block:

@spaces = [0...20].map (x)->
  [0...20].map (y) ->
    new Elements.Space(x, y)

The for loop version of this is also pretty simple:

@spaces = for x in [0...20]
  for y in [0...20]
    new Elements.Space(x, y)

Remember, everything is an expression. So this works (and might be a bit clearer than the map version).

like image 200
Aaron Dufour Avatar answered Sep 24 '26 02:09

Aaron Dufour



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!