简体   繁体   中英

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

I have the below scenario which has multiple if else conditions.

The cyclomatic complexity of the below code is showing as 7.

Is there a better way to write the below code snippet using Javascript which reduces the complexity of the code ?

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.

 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.

Maybe you should write "to reduce code" or "to make nicer code". There is no complexity in this if or else if statements.

Actually, Why don't you console.log the message from if/else if and you avoid to call another function?

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 has been found to take less incremental cost on subsequent conditions when compared with if-else conditionals. 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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