简体   繁体   English

如何降低 Javascript 中 if else 语句的复杂性?

[英]How to reduce the complexity of this if else statements in Javascript?

I have the below scenario which has multiple if else conditions.我有以下场景,其中有多个 if else 条件。

The cyclomatic complexity of the below code is showing as 7.以下代码的圈复杂度显示为 7。

Is there a better way to write the below code snippet using Javascript which reduces the complexity of the code ?是否有更好的方法来使用 Javascript 编写以下代码片段以降低代码的复杂性?

function setTime() {

var currentTime = "3/4/2020, 2:53:42 PM"
var selectedTime = "3/5/2020, 2:53:42 PM"

if( Date.parse(currentTime) < Date.parse(selectedTime)) {
    callThisMethod('Current time less than selected time');
} else if (Date.parse(currentTime) > Date.parse(selectedTime)) {
    callThisMethod('Current time Greater than selected time');
} else {
    callThisMethod('Current time is equal to selected time');
}
}

function callThisMethod(message) {
 console.log(message);
}

setTime();

One of the possible options:可能的选项之一:

const currentTime = new Date("3/4/2020, 2:53:42 PM"),
      selectedTime = new Date("3/5/2020, 2:53:42 PM")

callThisMethod(`Current time is ${currentTime < selectedTime ? 'less than' : currentTime > selectedTime ? 'greater than' : 'equal to'} selected time`)

You could get an ISO date first and then compare this dates.您可以先获取 ISO 日期,然后比较这些日期。

 function setTime() { var currentTime = "3/4/2020, 2:53:42 PM", selectedTime = "3/5/2020, 2:53:42 PM", current = new Date(currentTime).toISOString(), selected = new Date(selectedTime).toISOString(); if (current < selected) { callThisMethod('Current time less than selected time'); } else if (current > selected) { callThisMethod('Current time Greater than selected time'); } else { callThisMethod('Current time is equal to selected time'); } } function callThisMethod(message) { console.log(message); } setTime();

function setTime() {

    var currentTime = "3/4/2020, 2:53:42 PM";
    var selectedTime = "3/5/2020, 2:53:42 PM";
    let a = new Date(currentTime).getTime();
    let b = new Date(selectedTime).getTime();
    let str = ['less than','is equal','greater than'];
    let n = (a-b)/Math.abs(a-b) || 0;

    callThisMethod(`Current time ${str[n]} selected time`);
}

function callThisMethod(message) {
 console.log(message);
}

setTime();

According to https://jshint.com/ , the cyclomatic complexity number for this function is 2.根据https://jshint.com/ ,此函数的圈复杂度数为 2。

Maybe you should write "to reduce code" or "to make nicer code".也许您应该编写“以减少代码”或“编写更好的代码”。 There is no complexity in this if or else if statements.这个 if 或 else if 语句并不复杂。

Actually, Why don't you console.log the message from if/else if and you avoid to call another function?实际上,为什么不从 if/else if 中 console.log 消息,并且避免调用另一个函数?

function setTime() {
      var currentTime = "3/4/2020, 2:53:42 PM",
          selectedTime = "3/5/2020, 2:53:42 PM",
          current = new Date(currentTime).toISOString(),
          selected =  new Date(selectedTime).toISOString();

      if (current < selected) {
        console.log('Current time less than selected time');
      } else if (current > selected) {
        console.log('Current time Greater than selected time')
      } else {
        console.log('Current time is equal to selected time');
      }
    }

    setTime();

There could be several possible answers to this approach.这种方法可能有几种可能的答案。 One thing you could do is to keep the condition free from evaluations.您可以做的一件事是保持条件不受评估。 So instead of parsing date in condition expression parse it prior to comparing.因此,与其在条件表达式中解析日期,不如在比较之前解析它。 After that you could put the most frequent condition, that you feel might be the case often, as the first condition and break the other conditions using binary search approach.之后,您可以将最常见的条件,您认为可能经常出现的情况作为第一个条件,并使用二分搜索方法打破其他条件。 Consider following code snippet:考虑以下代码片段:

function setTime() {
    var currentTime = Date.parse("3/4/2020, 2:53:42 PM")
    var selectedTime = Date.parse("3/5/2020, 2:53:42 PM")
    if(currentTime < selectedTime) {
       callThisMethod('Current time less than selected time');
    } else {
       if (currentTime > selectedTime) {
         callThisMethod('Current time Greater than selected time');
       } else {
          callThisMethod('Current time is equal to selected time');
         }
      }
}

function callThisMethod(message) {
 console.log(message);
}

setTime();

Notice how conditionals are break into pieces using split technique.请注意如何使用拆分技术将条件分解为多个部分。 Or you could use switch case instead of conditionals.或者您可以使用 switch case 而不是条件。 Switch case has been found to take less incremental cost on subsequent conditions when compared with if-else conditionals.与 if-else 条件相比,已发现 switch case 在后续条件上花费的增量成本更少。 Consider following snippet:考虑以下片段:

function setTime() {
        var currentTime = Date.parse("3/4/2020, 2:53:42 PM")
        var selectedTime = Date.parse("3/5/2020, 2:53:42 PM")
        switch(true){
            case (currentTime > selectedTime):
                callThisMethod('Current time Greater than selected time');
                break;
            case (currentTime < selectedTime):
                callThisMethod('Current time less than selected time')
                break;
            default:
                 callThisMethod('Current time is equal to selected time')    
}
    }

    function callThisMethod(message) {
     console.log(message);
    }

    setTime();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM