Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I properly format long compound if statements in Coffeescript

Tags:

coffeescript

If I had a complex if statement that I did not want to overflow simply for aesthetic purposes, what would be the most kosher way to break it up since coffeescript will interpret returns as the body of the statement in this case?

if (foo is bar.data.stuff and foo isnt bar.data.otherstuff) or (not foo and not bar)   awesome sauce else lame sauce 
like image 994
Evan Avatar asked Jul 08 '11 15:07

Evan


People also ask

How do you break a long if statement?

Long if statements may be split onto several lines when the character/line limit would be exceeded. The conditions have to be positioned onto the following line, and indented 4 characters. The logical operators ( && , || , etc.)

How to comment in CoffeeScript?

Single-line Comments Whenever we want to comment a single line in CoffeeScript, we just need to place a hash tag before it as shown below. Every single line that follows a hash tag (#) is considered as a comment by the CoffeeScript compiler and it compiles the rest of the code in the given file except the comments.


1 Answers

CoffeeScript will not interpret the next line as the body of the statement if the line ends with an operator, so this is ok:

# OK! if a and not  b   c() 

it compiles to

if (a && !b) {   c(); } 

so your if could be formatted as

# OK! if (foo is  bar.data.stuff and  foo isnt bar.data.otherstuff) or  (not foo and not bar)   awesome sauce else lame sauce 

or any other line-breaking scheme so long as the lines end in and or or or is or == or not or some such operator

As to indentation, you can indent the non-first lines of your if so long as the body is even more indented:

# OK! if (foo is    bar.data.stuff and    foo isnt bar.data.otherstuff) or    (not foo and not bar)     awesome sauce else lame sauce 

What you cannot do is this:

# BAD if (foo  #doesn't end on operator!   is bar.data.stuff and    foo isnt bar.data.otherstuff) or    (not foo and not bar)     awesome sauce else lame sauce 
like image 69
nicolaskruchten Avatar answered Sep 24 '22 10:09

nicolaskruchten