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`)