I solved this but, my code seems so big and many repetitions.
My previous code was smaller but having issues in 5 test cases.
Here is the problem, Roman Numeral Converter.
Here is my code below -
function convertToRoman(num) {
let result = [];
let final = [];
let str = String(num);
//this loop is for beaking number to their positional value
for(let i=0; i<str.length; i++){
result.push(parseInt(str[i])*parseInt('1'+'0'.repeat((str.length-1)-i)));
}
//this function is for - number>= 1000
function thousands(x){
for(let i=0; i<x/1000; i++){
final.push("M");
}
}
//this function is for - number>= 100
function hundreds(x){
let subFinal = [];
if(x/100<4){
for(let i=0; i<x/100; i++){
subFinal.push('C');
}
final.push(subFinal.join(""));
}else if(x/100 === 4){
final.push('CD');
}else if(x/100 === 5){
final.push('D');
}else if(x/100 === 6){
final.push('DC');
}else if(x/100 === 7){
final.push('DCC');
}else if(x/100 === 8){
final.push('DCCC');
}else if(x/100 === 9){
final.push('CM');
}
}
//this function is for - number>= 10
function tens(x){
let subFinal = [];
if(x/10<4){
for(let i=0; i<x/10; i++){
subFinal.push('X');
}
final.push(subFinal.join(""));
}else if(x/10 === 4){
final.push('XL');
}else if(x/10 === 5){
final.push('L');
}else if(x/10 === 6){
final.push('LX');
}else if(x/10 === 7){
final.push('LXX');
}else if(x/10 === 8){
final.push('LXXX');
}else if(x/10 === 9){
final.push('XC');
}
}
//this function is for - number< 10
function units(x){
let subFinal = [];
if(x<4){
for(let i=0; i<x; i++){
subFinal.push('I');
}
final.push(subFinal.join(""));
}else if(x === 4){
final.push('IV');
}else if(x === 5){
final.push('V');
}else if(x === 6){
final.push('VI');
}else if(x === 7){
final.push('VII')
}else if(x === 8){
final.push('VIII')
}else if(x === 9){
final.push('IX');
}
}
//this loop is to convert all positional value to roman numerals
for(let i=0; i<str.length; i++){
if(result[i]>=1000){
thousands(result[i]);
}else if(result[i]>=100){
hundreds(result[i]);
}else if(result[i]>=10){
tens(result[i]);
}else{
units(result[i]);
}
}
return final.join("");
}
Feel free to suggest me to make my code more smart