I have this piece of code that checks the input of a text box before I compute for my main logic. This looks like it should be refactored but I'm currently stumped how to do so. The only thing that comes to mind is to make 2 functions "processDecimal" and "processInt" and I just copy the code under their respective if condition but it just feels wrong. Any help?
function inputChanges(element) {
let elm = document.getElementById(element.id);
let val = elm.value;
let isDecimal = elm.hasAttribute("decimal") ? true : false;
if (isDecimal) {
if (parseFloat(val) == 0 || val == "") {
elm.value = "0.00";
} else {
elm.value = isNaN(parseFloat(val)) ? "0.00" : parseFloat(val).toFixed(2);
}
}else {
if (parseInt(val) == 0 || val == "") {
elm.value = "0";
} else {
elm.value = isNaN(parseInt(val)) ? "0" : parseInt(val);
}
}
computeTemperature();
}
1 Answer 1
I would say
if (parseFloat(val) == 0 || val == "") {
elm.value = "0.00";
} else {
elm.value = isNaN(parseFloat(val)) ? "0.00" : parseFloat(val).toFixed(2);
}
is redundant. You can simply use elm.value = isNaN(parseFloat(val)) ? "0.00" : parseFloat(val).toFixed(2);
.
The same holds true for the integer evaluation. This
if (parseInt(val) == 0 || val == "") {
elm.value = "0";
} else {
elm.value = isNaN(parseInt(val)) ? "0" : parseInt(val);
}
can be reduced to elm.value = isNaN(parseInt(val)) ? "0" : parseInt(val);
From a "Code Smell" perspective, it reduces cognitive complexity by reducing the number of logical paths