Coffeescript assoc array syntax in a list comprehension
Hi everyone: I'm often running into the following issue with coffeescript and was wondering if anyone knows of a solution. Consider the following code:
k=for x in [0...3]
{foo:{bar:x,baz:3},qux:5}
I have a lot of code that has this basic layout. However, it is hard to read. It would be cleaner to write this code in the following manner:
#Gives Error- PARSE ERROR ON LINE 5: UNEXPECTED 'TERMINATOR'
k=for x in [0...3]
foo:
bar:x
baz:3
qux:5
This error can be ci开发者_如何转开发rcumvented with the following hack, which looks really ugly:
k=for x in [0...3]
g=
foo:
bar:x
baz:3
qux:5
g
Does anybody know a clean way to use Coffeescript's multi-line assoc array syntax inside of a comprehension without running into this error? Thanks for your help!
So,
k=for x in [0...3]
foo:
bar:x
baz:3
qux:5
fails to compile, but
func
foo:
bar:x
baz:3
qux:5
(for instance) compiles correctly. I believe this is a known bug in the CoffeeScript parser. Unfortunately, there are several similar issues open, as parsing YAML-style objects has turned out to be exceptionally tricky. So for now, I'd use explicit curly braces, as c3rin suggests.
[Edit: See issue 981 specifically.]
.map()
is your friend here:
k = [0...3].map (i) ->
foo:
bar: "#{i}"
baz: i
qux: i*3
(i know your problem is actually a bug, but this makes more sense IMO. list comprehensions are better suited to simple tasks)
I've changed my answer a couple of times, but I think the issue with your first example is that coffeescript compiler thinks that foo: is the object you want to build and is concerned when it gets to qux: because it thinks its a different object altogether than foo. What's interesting is that you can mix the JSON-style and YAML-style declarations, using the JSON-style curly braces to explicitly declare the boundaries of the object definition, and the use YAML inside of the boundaries for readability.
{
foo:
bar:x
baz:3
qux:5
}
My usual solution for this is the following:
k = for x in [0...3]
g =
foo:
bar:x
baz:3
qux:5
Setting a variable returns the value it is set to. Its still a bit hacky, but slightly nicer than your version that explicitly returns g
after setting it. Definitely a workaround for a coffeescript bug, though.
精彩评论