So while I was solving the Roman Numeral Converter Challenge I have come upon what I consider an important realisation (for me atleast).
You can find this challenge here:
Roman Numerals
So what I realised is that I don’t really have to make a converter. I just need an object that holds the valus of roman numerals for Units, Tens, Hundreds and Thousands…
Should I desire to convert Tens-of-Thousands or more, I will simply add another property that holds the value for each Ten-Thousand.
Since each value (unit, ten, hundred…) is represented with an integer from 0-9, I can just pull the corresponding roman numeral from romanObj.
I was kind of shocked that I couldn’t find this solution… After all, it is easy to maintain and understand.
Here is my code:
function convertToRoman(num) {
let romanArr = [];
const romanObj = {
0: ["","I","II","III","IV","V","VI","VII","VIII","IX"],
1: ["","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"],
2: ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"],
3: ["","M","MM","MMM","MV","V","VM","VMM","VMMM","IX"]
}
const numArrRep = num.toString().split("").map(item => parseInt(item));
let m = numArrRep.length - 1;
for(let n = m; n >= 0; n--) {
romanArr.push(romanObj[n][numArrRep[m - n]]);
}
return romanArr.join("");
}
convertToRoman(3999);
What would you say the drawbacks of such an approach would be?