javascript - 重构复杂 if 表达式的最佳方法

标签 javascript angularjs if-statement expression

我刚刚加入一个大型电子商务项目,该项目有一个 angularJS 前端。我的任务是向结账页面添加许多复杂的功能……这些页面已经有很多复杂的逻辑。

为了让事情变得更困难,我不断遇到很多 if像下面这样的语句表达式很难理解,并且使用许多此类 if 来浏览此代码是一个缓慢的过程。表达式。

其中一些表达式非常关键,有时甚至更长......没有单元测试,当我询问其他开发人员这正在检查什么以及为什么(只是为了确保我理解)时,我通常会指出某人其他而不是解释。

if ((!previousBillingAddress) || (previousBillingAddress && previousBillingAddress.id !== bag.paymentAddress.id)){
    console.log('all of the above was true'); // just a dummy log
} else {
    console.log('all of the above was false'); // just a dummy log
}

有人对重构这些类型的表达式有好的建议吗?

我想将它们分解为具有描述性名称的函数,并且函数可以返回 truefalse但我不确定是否有更好的方法。

最佳答案

要有

A = previousBillingAddress 
B = previousBillingAddress.id !== bag.paymentAddress.id

那么你的表达是:

if (!A || (A && B)) {
  log1
} else {
  log2
}

我们可以用!A || (A && B)做什么?它等于!A || B :

A   |  B  |  !A  |  A && B  |  !A || (A && B)  |  !A || B
==========================================================
1   |  1  |   0  |    1     |        1         |     1
1   |  0  |   0  |    0     |        0         |     0
0   |  1  |   1  |    0     |        1         |     1
0   |  0  |   1  |    0     |        1         |     1

这就是为什么你的表达式等于:

if (!previousBillingAddress || previousBillingAddress.id !== bag.paymentAddress.id) {
    console.log('all of the above was true'); // just a dummy log
} else {
    console.log('all of the above was false'); // just a dummy log
}

TL;DR

上表仅检查是否 !A || (A && B)等于!A || B 。怎么猜!A || B ?如果出现此类表达式,最好遵循以下规则:

A == !(!(A))                        (rule 1)
!(A && B) == !A || !B               (rule 2)
!(A || B) == !A && !B               (rule 3)
A && (B || C) == A && B || A && C   (rule 4)

所以我们有!A || (A && B) , 让我们玩。根据规则 1,它等于

!(!(!A || (A && B)))

现在我们使用规则 3:

!(!(!A || (A && B))) == !(A && !( A && B))

规则 2:

!(A && !( A && B)) == !(A && (!A || !B))           (*)

由于规则 4:

A && (!A || !B) == (A && !A) || (A && !B) 

我们有(A && !A) || (A && !B)可以减少为(A && !B) 。现在我们可以回到(*)我们有:

!(A && (!A || !B)) == !((A && !A) || (A && !B)) == !(A && !B)

根据规则 2,我们得到:

!(A && !B) == !A || B

关于javascript - 重构复杂 if 表达式的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39358256/

相关文章:

javascript - 将变量从 .CTP View 设置为 .JS

javascript - 使用 es2015 map 获取索引失败

javascript - 复制 $ ('div' ).html() 期待一些特定的文本

javascript - 在服务不工作的 Controller 之间传递数据

此修订版需要代码建议

python - 如何创建随机范围,但排除特定数字?

java - 如何使用 javascript 在 IE10 中获取已安装的 JRE/Java 版本

c# - 如何在 AngularJS 中将参数传递给 DELETE?

javascript - AngularJS状态提供者多参数

c - 与 0.9 相比,为什么 >= 运算符在 C 中与 > 运算符一样工作