如何在 Coffeescript 中正确格式化长复合 if 语句
如果我有一个复杂的 if 语句,我不想仅仅出于美观目的而溢出,那么分解它的最合理的方法是什么,因为在这种情况下,coffeescript 会将 return 解释为语句的主体?
if (foo is bar.data.stuff and foo isnt bar.data.otherstuff) or (not foo and not bar)
awesome sauce
else lame sauce
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(5)
如果该行以运算符结尾,CoffeeScript 不会将下一行解释为语句的主体,因此这是可以的:
它会编译为
您的
if
可以格式化为或任何其他换行方案只要行以
and
或or
或is
或==
或not 或一些这样的运算
符至于缩进,您可以缩进非第一个只要正文更加缩进,您的
if
行就可以了:您不能做的是:
CoffeeScript will not interpret the next line as the body of the statement if the line ends with an operator, so this is ok:
it compiles to
so your
if
could be formatted asor any other line-breaking scheme so long as the lines end in
and
oror
oris
or==
ornot
or some such operatorAs to indentation, you can indent the non-first lines of your
if
so long as the body is even more indented:What you cannot do is this:
这会在一定程度上改变代码的含义,但可能会有一些用处:
请注意
is...isnt
链,它是合法的,就像a
a
b< c
在 CoffeeScript 中是合法的。当然,蹩脚酱
的重复是不幸的,你可能不想立即返回
。另一种方法是使用 soaks 来编写if foo and
有点不优雅;如果foo
不可能是undefined
,那么您可以丢弃它。This changes your code's meaning somewhat, but may be of some use:
Note the
is...isnt
chain, which is legit, just asa < b < c
is legit in CoffeeScript. Of course, the repetition oflame sauce
is unfortunate, and you may not want toreturn
right away. Another approach would be to use soaks to writeThe
if foo and
is a little inelegant; you could discard it if there's no chance thatfoo
isundefined
.就像任何其他语言一样,首先就没有它们。给不同的部分命名并分别对待它们。要么通过声明谓词,要么只是创建几个布尔变量。
Like any other language, by not having them in the first place. Give names to the different parts an treat them separately. Either by declaring predicates, or by just creating a couple of boolean vars.
对我来说,转义换行符看起来最具可读性:
Escaping the linebreak looks most readable to me:
当出现大量低级样板文件时,您应该提高抽象级别。
最好的解决方案是:
使用好的命名变量和函数
逻辑规则之一是:
第一种方法。 变量:
这种方法的主要缺点是速度慢。如果我们使用
and
和or
运算符功能并用函数替换变量,我们将获得更好的性能:如果
A
为 false 运算符and
不会调用如果
A
为 true 运算符or
不会调用第二种方式。 功能:
When a lot of low-level boilerplate occurs you should increase level of abstract.
The best solutions are:
to use good named variables and functions
logic rules in if/else statements
One of logic rules is:
The first way. Variables:
The main disadvantage of this method is its slowness. We will get better performance if we use
and
andor
operators features and replace variables with functions:If
A
is false operatorand
wouldnt callIf
A
is true operatoror
wouldnt callThe second way. Functions: