0
\$\begingroup\$

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();
}
asked Feb 21, 2023 at 7:51
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

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

answered Feb 21, 2023 at 18:46
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.