Reputation: 123
JavaScript Don't make funcitons within a loop and showing Cyclomatic complexity. I can not get around JSHint's error message. Here is the loop I am using:
var keys = document.querySelectorAll('#calculator span');
var operators = ['+', '-', 'x', '÷'];
var decimalAdded = false;
for (var i = 0; i < keys.length; i++) {
keys[i].onclick = function (e) {
var input = document.querySelector('.screen');
var inputVal = input.innerHTML;
var btnVal = this.innerHTML;
if (btnVal === 'C') {
input.innerHTML = '';
decimalAdded = false;
} else if (btnVal === '=') {
var equation = inputVal;
var lastChar = equation[equation.length - 1];
equation = equation.replace(/x/g, '*').replace(/÷/g, '/');
if (operators.indexOf(lastChar) > -1 || lastChar === '.'){
equation = equation.replace(/.$/, '');
}
if (equation){
input.innerHTML = (new Function('return ' + equation))();
}
decimalAdded = false;
} else if (operators.indexOf(btnVal) > -1) {
var lastChar = inputVal[inputVal.length - 1];
if (inputVal !== '' && operators.indexOf(lastChar) === -1){
input.innerHTML += btnVal;
}
else if (inputVal === '' && btnVal === '-'){
input.innerHTML += btnVal;
}
if (operators.indexOf(lastChar) > -1 && inputVal.length > 1) {
input.innerHTML = inputVal.replace(/.$/, btnVal);
}
decimalAdded = false;
} else if (btnVal === '.') {
if (!decimalAdded) {
input.innerHTML += btnVal;
decimalAdded = true;
}
} else {
input.innerHTML += btnVal;
}
e.preventDefault();
};
}
How to reduce Cyclomatic complexity number for this function is 12
Upvotes: 2
Views: 362
Reputation: 5022
Okay, so cyclomatic complexity is basically a measure of the number of possible paths through a function. So it multiplies up all the loops and conditionals. You've got a for()
loop with a whole stack of nested if()
and else
blocks inside it, so yes, that will give a very large complexity score.
The way to reduce it is to split that code into multiple functions. Each function should do part of the job, and will therefore have a lower complexity score. Because complexity multiplies up with each conditional, splitting them will result in several functions with a much lower total complexity.
Exactly how you break up the functions is up to you, but the general advice is to break them down as much as possible; the ideal function is one that does just one thing, and nothing more.
Upvotes: 1