I solved the challenge but I realize how ineffective it is. Can you give me feedback on my code like and maybe share how did you solved yours and how could I make it better/shorter?
Heard that this was an interview question in some companies. Will probably fail the interview with a long convoluted code like this. A lot of actions are being repeated and I think it could be shorted with some short of recursion but not exactly sure.
**My code so far**
Click here to view my solution of Roman Numeral Converter
function convertToRoman(num) {
let valR = { 1: 'I', 5: 'V', 10: 'X', 50: 'L', 100: 'C', 500: 'D', 1000: 'M' };
let len = num.toString().length;
if (len === 1 && valR.hasOwnProperty(num)) {
return valR[num];
}
let firstD, remD, roman = [];
rome(num);
function rome(num) {
len = num.toString().length;
switch (len) {
case 1:
if (valR.hasOwnProperty(num)) { roman.push(valR[num]); }
else if (num <= 3) {
roman.push(valR[1].repeat(num));
}
else if (num - 5 >= 4) {
roman.push(valR[1]);
roman.push(valR[10]);
}
else if (num - 5 < 4) {
if (num - 5 > 0) {
roman.push(valR[5]);
roman.push(valR[1].repeat(Math.abs(num - 5)))
}
else {
roman.push(valR[1].repeat(Math.abs(num - 5)));
roman.push(valR[5]);
}
}
break;
case 2:
firstD = parseInt(num / 10); //9
remD = num % 10; //7
if (firstD <= 3) {
roman.push(valR[10].repeat(firstD));
rome(remD);
}
else if (firstD - 5 >= 4) {
roman.push(valR[10].repeat(10 - firstD));
roman.push(valR[100]);
rome(remD);
}
else if (firstD - 5 < 4) {
if (firstD - 5 > 0) {
roman.push(valR[50]);
roman.push(valR[10].repeat(Math.abs(firstD - 5)))
}
else {
roman.push(valR[10].repeat(Math.abs(firstD - 5)));
roman.push(valR[50]);
}
rome(remD);
}
break;
case 3:
firstD = parseInt(num / 100);//6
remD = num % 100; //49
if (firstD <= 3) {
roman.push(valR[100].repeat(firstD));
rome(remD);
}
else if (firstD - 5 >= 4) {
roman.push(valR[100].repeat(10 - firstD));
roman.push(valR[1000]);
rome(remD);
}
else if (firstD - 5 < 4) {
if (firstD - 5 > 0) {
roman.push(valR[500]);
roman.push(valR[100].repeat(Math.abs(firstD - 5)))
}
else {
roman.push(valR[100].repeat(Math.abs(firstD - 5)));
roman.push(valR[500]);
}
rome(remD);
}
break;
case 4:
firstD = parseInt(num / 1000);
if (firstD <= 3) {
roman.push(valR[1000].repeat(firstD));
}
remD = num % 1000;
rome(remD);
break;
}
}
roman = roman.join("");
console.log(roman);
return roman;
}
convertToRoman(3999);
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36 OPR/76.0.4017.177
Challenge: Roman Numeral Converter
Link to the challenge: