0

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?

2
  • 1
    I guess you could say is instead of == if you really wanted to. They both mean === Commented Dec 14, 2012 at 14:37
  • 1
    Many people avoid the is and use plain old ==. This way you are more compatible with the majority of developers. I also prefer to use if object then x else y (JavaScript's magic check for "", undefined, false, null, 0) which works fine in many places. Commented Dec 14, 2012 at 15:38

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I am not sure the unless is a problem, I actually like it. Also, the use of is helps the reading :) advances.push (0 - advance) unless advance is 0
No I don't like that way. It is already hard to tell my colleagues about coffee-script anyway. And adding new words for very common things such as == and if just opens the door hell. ;)
Yeah you've got a point here. Not a real problem anyway, your answer is good as it is.
IMO splitting the same piece of code as in question into four line gives actually something cleaner and more readable than what I and you proposed in our answers.
0

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]

Comments

0

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)])

http://underscorejs.org/#uniq

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.