I came to a point where I needed to check a condition and proceed with another condition if its true for many times.
Here I'm using fromNS
string which has the base of number (like - binary, decimal, octal) and then a condition to check if the
fromValue
is a valid number using regex.
If the value is invalid as per the base then displayError()
function is called.
from.addEventListener("input", function () {
fromValue = from.value;
// Is this method efficient
if((fromNS == "Binary" && !/^[01]*$/.test(fromValue)) ||
(fromNS == "Decimal" && !/^[0-9]*$/.test(fromValue)) ||
(fromNS == "Hexadecimal" && !/^[0-9a-fA-F]*$/.test(fromValue)) ||
(fromNS == "Octal" && !/^[0-7]*$/.test(fromValue)))
displayError();
// Or should I use this
switch (fromNS) {
case "Binary":
if(!/^[01]*$/.test(fromValue)) displayError();
break;
case "Decimal":
if(!/^[0-9]*$/.test(fromValue)) displayError();
break;
case "Hexadecimal":
if(!/^[0-9a-fA-F]*$/.test(fromValue)) displayError();
break;
case "Octal":
if(!/^[0-7]*$/.test(fromValue)) displayError();
break;
}
});
I would go with one of these:
const conditions = [
formNS === "Binary" && !/^[01]*$/.test(form.value),
formNS === "Decimal" && !/^[0-9]*$/.test(form.value),
formNS === "Hexadecimal" && !/^[0-9a-fA-F]*$/.test(form.value),
formNS === "Octal" && !/^[0-7]*$/.test(form.value),
];
if (conditions.some(Boolean) {
displayError();
}
const conditions = [
{ ns: "Binary", regex: /^[01]*$/ },
{ ns: "Decimal", regex: /^[0-9]*$/ },
{ ns: "Hexadecimal", regex: /^[0-9a-fA-F]*$/ },
{ ns: "Octal", regex: /^[0-7]*$/ },
];
if (conditions.some(({ ns, value }) => formNS === ns && !value.match(regex))) {
displayError();
}
switch (true) {
case formNS === "Binary" && !/^[01]*$/.test(form.value):
case formNS === "Decimal" && !/^[0-9]*$/.test(form.value):
case formNS === "Hexadecimal" && !/^[0-9a-fA-F]*$/.test(form.value):
case formNS === "Octal" && !/^[0-7]*$/.test(form.value):
displayError();
}