I'm looking for some feedback on this converter I made. It works just fine for the instructions I had, but I'm wondering what else could be done to improve it or if there's a better aproach to doing this. I wasn't expecting to nail this since I'm just starting to learn JS.
I'm aware I could've implemented things like Math.floor(), Math.min() to make the validations, I'm mostly wondering on the conversion itself, what else could be optimized, I'm sure there was an easier way. I also thought of using forEach() instead of multiple for() and arrays but I'm not sure how
Here's the whole thing in codepen: Roman Numeral Converter
Here's the JS code itself:
const numberInput = document.getElementById("number");
const convertButton = document.getElementById("convert-btn");
const output = document.getElementById("output");
function convertRom () {
const numbersList = numberInput.value.split((/(\d)/)).filter(Boolean)
for (let i = numbersList.length; numbersList.length < 4; i--) {
numbersList.unshift('0');
i -= 1
}
console.log("numbersList " + numbersList);
const romanDigit1 = [];
const romanDigit2 = [];
const romanDigit3 = [];
const romanDigit4 = [];
for (let digit1 = numbersList[0]; digit1 > 0; digit1 -1){
romanDigit1.push("M");
digit1 -= 1
}
for (let digit2 = Number(numbersList[1]); digit2 > 0; digit2 === digit2){
if (digit2 === 9) {
romanDigit2.push("CM")
digit2 -= 9;
} else if (digit2 === 5){
romanDigit2.unshift("D")
digit2 -= 5;
} else if (digit2 === 4){
romanDigit2.push("CD")
digit2 -= 4;
} else {
romanDigit2.push("C");
digit2 -= 1
}
}
for (let digit3 = Number(numbersList[2]); digit3 > 0; digit3 === digit3){
if (digit3 === 9) {
romanDigit3.push("XC")
digit3 -= 9;
} else if (digit3 === 5){
romanDigit3.unshift("L")
digit3 -= 5;
} else if (digit3 === 4){
romanDigit3.push("XL")
digit3 -= 4;
} else {
romanDigit3.push("X");
digit3 -= 1
}
}
for (let digit4 = Number(numbersList[3]); digit4 > 0; digit4 === digit4){
if (digit4 === 9) {
romanDigit4.push("IX")
digit4 -= 9;
} else if (digit4 === 5){
romanDigit4.unshift("V")
digit4 -= 5;
} else if (digit4 === 4){
romanDigit4.push("IV")
digit4 -= 4;
} else {
romanDigit4.push("I");
digit4 -= 1
}
}
const romanResult = romanDigit1.join("") + romanDigit2.join("") + romanDigit3.join("") + romanDigit4.join("");
output.innerHTML = romanResult;
}
function validate() {
switch (true){
case numberInput.value === "":
output.innerHTML = "Please enter a valid number";
numberInput.value = "";
break
case numberInput.value <= 0:
output.innerHTML = "Please enter a number greater than or equal to 1";
numberInput.value = "";
break
case numberInput.value >= 4000:
output.innerHTML = "Please enter a number less than or equal to 3999";
numberInput.value = "";
break
default:
convertRom();
}
}
convertButton.addEventListener("click", validate)