如何在Coffeescript中正确格式化长复合if语句

Eva*_*van 68 coffeescript

如果我有一个复杂的if语句,我不想​​仅仅为了审美目的而溢出,那么什么是最合适的方式来解决它,因为coffeescript会将返回解释为在这种情况下语句的主体?

if (foo is bar.data.stuff and foo isnt bar.data.otherstuff) or (not foo and not bar)
  awesome sauce
else lame sauce
Run Code Online (Sandbox Code Playgroud)

nic*_*ten 86

如果行以操作符结束,CoffeeScript将不会将下一行解释为语句的主体,因此这是正常的:

# OK!
if a and
not 
b
  c()
Run Code Online (Sandbox Code Playgroud)

它编译成

if (a && !b) {
  c();
}
Run Code Online (Sandbox Code Playgroud)

所以你if可以格式化为

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

或任何其他的换行方案,只要该线中结束andoris==not或一些这样的操作者

至于缩进,if只要主体更加缩进,你可以缩进你的非第一行:

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

你不能做的是:

# 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
Run Code Online (Sandbox Code Playgroud)

  • 如果你不想缩写`if`statmenet的主体"更多",你可以使用`then`,从与`if`相同的级别开始.它更具可读性,恕我直言. (2认同)