I just finished the second task before getting my certificate - a Roman number converter. However after checking the answers and comparing them with my code I felt like if I have hardcoded it.
I would like to know the opinion of someone with more experience and know if I need to go back and do it again in other way.
function convertToRoman(num) {
var ans = "";
var d4 = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"];
var d3 = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", "C"];
var d2 = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"];
var d1 = ["", "M", "MM", "MMM"]
var strnum = String(num)
switch (strnum.length) {
case 1:
ans = d4[Number(strnum)];
break;
case 2:
ans = d3[Number(strnum[0])] + d4[Number(strnum[1])];
break;
case 3:
ans = d2[Number(strnum[0])] + d3[Number(strnum[1])] + d4[Number(strnum[2])];
break;
case 4: ans = d1[Number(strnum[0])] + d2[Number(strnum[1])] + d3[Number(strnum[2])] + d4[Number(strnum[3])];
}
console.log(ans)
return ans;
}
convertToRoman(1004);