Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays of Literals in Coffeescript

Tags:

coffeescript

When creating an array of literals in JS:

[{ name: 'david', value: 'blue' }, { name: 'harold', value: 'orange' }]

The only way I can see of writing this in Coffeescript is:

[
  name: 'david'
  value: 'blue'
,
  name: 'harold'
  value: 'orange'
]

To me this is pretty ugly, that "floating" comma doesn't really sit well. Are there any alternative syntaxes for this? I am aware you can continue to use a JS-style approach from within Coffeescript but I was hoping for something more concise.

like image 371
Colin Ramsay Avatar asked May 24 '12 13:05

Colin Ramsay


3 Answers

I can't remember why this works, or even if it's useful to you, but it's another alternative to the code you're writing.

[
  {}= name: 'david', value: 'blue'
  {}= name: 'harold', value: 'orange'
]

Yes, this seems to work.

This also weirdly seems to work. I'm sure there's a simple reason for it, but I'm not sure of it.

[
  {}= 
    name: 'david'
    value: 'blue'
  {}= 
    name: 'harold'
    value: 'orange'
  {}= 
    name: 'david'
    value: 'blue'
]

See the compiled code.

like image 197
Sandro Avatar answered Nov 17 '22 17:11

Sandro


This has been the one thing that every CoffeeScript developer seems to run into.

I'm afraid it's all we have for now. The only other alternative I can think of is:

[
  { name: 'david', value: 'blue' }
  { name: 'harold', value: 'orange' }
]

… but it's far from ideal itself.

If anyone wanted to suggest an alternate, concise and CS-y syntax, I'd be happy to try to implement it in the parser and make a pull request for it. I'd love to have better than this.

like image 11
Asherah Avatar answered Nov 17 '22 17:11

Asherah


To get rid of the commas inside the object literals you can go for:

[
  {
    name: 'david'
    value: 'blue'
  }, {
    name: 'harold'
    value: 'orange'
  }, {
    name: 'david'
    value: 'blue'
  }
]

Or, if you really hate commas:

[
  {
    name: 'david'
    value: 'blue'
  }
  {
    name: 'harold'
    value: 'orange'
  }
  {
    name: 'david'
    value: 'blue'
  }
]

Though i personally feel that the floating commas, indented one level, don't look so bad:

[
    name: 'david'
    value: 'blue'
  , 
    name: 'harold'
    value: 'orange'
  , 
    name: 'david'
    value: 'blue'
]

I think it makes it pretty obvious when object literals start and finish and it also makes it nearly impossible to forget a comma between object literals =D

like image 8
epidemian Avatar answered Nov 17 '22 17:11

epidemian