Reputation: 28780
I have the following array assignment:
advances = if advance == 0 then [advance] else [advance, (0 - advance)]
I wonder if there is a more coffeescript way of doing this?
Upvotes: 0
Views: 140
Reputation: 3412
I think your own proposal is perfectly fine. It's simple, clear, and pure-functional.
If you think minimizing punctuation is part of the coffeescript way then you could drop the parentheses
advances = if advance == 0 then [advance] else [advance, 0 - advance]
Upvotes: 0
Reputation: 10824
What about:
advances = [advance]
advances.push (0 - advance) if advance != 0
I think this is a bit more readable. But I guess that a matter of taste. It also uses coffee-script's nice if-at-the-end feature, which I makes some statements such as this "conditional array growing" more readable (for me at least).
PS: I also changed the == 0
to != 0
to avoid the unless
statement. It just confuses me when reading code.
PPS: Don't put everything on one line just for the sake of it (even if is coffee-script is good at that). Always think of the most readable (and well performing) code.
Upvotes: 1
Reputation: 12665
You're perhaps thinking about list comprehensions, but I can't imagine how to utilize them here. I believe you'd get better result utilizing underscore.js (or some other library providing collection utilities):
advances = _.uniq([advance, (0 - advance)])
Upvotes: 0