So I'm currently learning JavaScript and the lecturer who taught the course I'm currently watching constantly talks about reducing cyclomatic complexity. He uses a few tricks for doing so which I cannot understand. I think I understand why a switch statement replaced by a map reduces the cyclomatic complexity - from many possible cases there is only one. However, he has been doing something like the following to reduce cyclomatic complexity:
if (condition) {
arr.push(element);
} else {
arr.pop();
}
becomes:
const actionsMap = {true: "push", false: "pop"};
arr[actionsMap[condition]](element);
I prefer the second one, but how does it reduce the cyclomatic complexity? There are still two cases which are now only called in another way. If that really reduces cyclomatic complexity, can every if be replaced with a map with true and false keys to reduce cyclomatic complexity? He also uses || and && to reduce the cyclomatic complexity, but I've seen them listed as part of the cyclomatic complexity. How does this reducing of cyclomatic complexity work? Isn't it just a different shape for the same condition?
Edit: I do realize there are switch statements which cannot be so easily replaced by a map. Thank you for pointing out the reduced maintainability, but my question is: How does the reduction of complexity work here? Why is the actionsMap better than the if. Is it not a condition? Also, how do the logical operators reduce complexity?
return (a>5 && a) || a-1;
How is this better than the following in terms of cyclomatic complexity:
if (a>5) return a;
else return a-1;
I know the examples are not of production quality code, but they illustrate my point pretty well.