Question about the second challenge in the JS course

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);

Hi @ovi.muradyan !

I have added spoiler tags around your code since this is a full working solution.

ok, thanks, pardon me

You can pull a bit of a trick to decrease the number of strings/cases you are keeping track of, but overall I think your solution is very reasonable.

Here’s mine. Its a bit more terse syntax, but in here I reduced some of the repetition that’s in your cases for 2, 3, 6, 7, 8 (and 20, 30, … ect)

function convertToRoman(num) {
  // Numerals
  const romanNumerals = {
    1000 : "M",
    900  : "CM",
    500  : "D",
    400  : "CD",
    100  : "C",
    90   : "XC",
    50   : "L",
    40   : "XL",
    10   : "X",
    9    : "IX",
    5    : "V",
    4    : "IV",
    1    : "I",
  };
  const arabicNumerals = Object.keys(romanNumerals)
    .sort((a, b) => b - a);
  // Decrement number while building roman numeral version
  return arabicNumerals.reduce(
    (romanNum, arabic) => {
      while (num >= arabic) {
        num -= arabic;
        romanNum += romanNumerals[arabic];
      }
      return romanNum;
    },
    "");
}

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.