Hey all,
I recently completed my Roman Numeral Translator Solution and I would appreciate any thoughts anyone would care to share with me.
I was trying to avoid hard-coding anything so it is a little verbose.
let numeralStr;
function convertToRoman(num) {
numeralStr = "";
const roman = { 1000: "M", 500: "D", 100:"C", 50:"L", 10:"X", 5:"V", 1:"I" };
let ctr = num;
let romanKeys = [ ...Object.keys(roman) ].reverse();
romanKeys.forEach(key =>{
let dec = decrementer(key);
dec, ctr = filter(dec, key, ctr, roman);
if(ctr >= key - dec){
dec, ctr = filter(dec, key, ctr, roman);
}
});
return numeralStr;
}
function filter(dec, key, ctr, roman){
if(ctr > +key && ctr > 0){
let mult = Math.floor(ctr / +key);
for(let i = 0; i < mult; i++){
numeralStr += roman[key];
}
ctr -= +key * mult;
return ctr;
}
if( ctr >= +key){
numeralStr += roman[key];
ctr -= +key;
return ctr;
}
if(ctr >= +key - dec && ctr > 0 && dec !== 0){
numeralStr += roman[dec];
numeralStr += roman[key];
ctr -= (+key - dec);
return ctr;
}
return ctr;
}
function decrementer(num){
let numArr = `${num}`;
numArr = numArr.split("");
let newNum;
if(numArr[0] === "1" && num >= 10){
newNum = num * 1/10;
}
if (numArr[0] === "5" && num >= 5){
newNum = num * 1/5;
}
if(numArr === "1"){
newNum = 0;
}
return newNum;
};
console.log( convertToRoman(14) );
Let me know your thoughts if you wish to.
Gabe