Hi there!
I just completed the Roman Numeral Converter project and I feel that it’s extremely repetitive with the if statements and/or there maybe a better way to doing this.
I originally used a ton of while
loops to complete the project, however, I went back at it and tried to use recursion instead of 13 while loops, but I still ended up with repetitive If
statements.
function convertToRoman(num) {
let romanNumeralStr = [];
function numeralParse (numIndex) {
//Roman Numeral M
if (numIndex >= 1000) {
romanNumeralStr.push("M");//Pushes M into romanNum array.
numIndex -= 1000;//Reduces our numIndex by 1000.
/*Pushes numIndex back into this function and checks
if numIndex is still greater than or equal to 1000.
If it is not, it checks for 900 then 500 then 400 etc */
return numeralParse(numIndex);
}
//Roman Numeral CM
if (numIndex >= 900) {
romanNumeralStr.push("CM");
numIndex -= 900;
return numeralParse(numIndex);
}
//Roman Numeral D
if (numIndex >= 500) {
romanNumeralStr.push("D");
numIndex -= 500;
return numeralParse(numIndex);
}
//Roman Numeral CD
if (numIndex >= 400) {
romanNumeralStr.push("CD");
numIndex -= 400;
return numeralParse(numIndex);
}
//Roman Numeral C
if (numIndex >= 100) {
romanNumeralStr.push("C");
numIndex -= 100;
return numeralParse(numIndex);
}
//Roman Numeral XC
if (numIndex >= 90) {
romanNumeralStr.push("XC");
numIndex -= 90;
return numeralParse(numIndex);
}
//Roman Numeral L
if (numIndex >= 50) {
romanNumeralStr.push("L");
numIndex -= 50;
return numeralParse(numIndex);
}
//Roman Numeral XL
if (numIndex >= 40) {
romanNumeralStr.push("XL");
numIndex -= 40;
return numeralParse(numIndex);
}
//Roman Numeral X
if (numIndex >= 10) {
romanNumeralStr.push("X");
numIndex -= 10;
return numeralParse(numIndex);
}
//Roman Numeral IX
if (numIndex >= 9) {
romanNumeralStr.push("IX");
numIndex -= 9;
return numeralParse(numIndex);
}
//Roman Numeral V
if (numIndex >= 5) {
romanNumeralStr.push("V");
numIndex -= 5;
return numeralParse(numIndex);
}
//Roman Numeral IV
if (numIndex >= 4){
romanNumeralStr.push("IV");
numIndex -= 4;
return numeralParse(numIndex);
}
//Roman Numeral I
if (numIndex >= 1) {
romanNumeralStr.push("I");
numIndex -= 1;
return numeralParse(numIndex);
}
return numIndex;
}
numeralParse(num);
romanNumeralStr = romanNumeralStr.join("");
console.log(romanNumeralStr);
return romanNumeralStr;
}
convertToRoman(1004);
My apologies if you have a hard time reading my code and thank you in advance!