JavaScript Algorithms and Data Structures Projects - Roman Numeral Converter

Tell us what’s happening:

My code is not producing the desired output for number 4 and numbers greater than 4.

Your code so far

function convertToRoman(num) {
  let numerals = {
    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"
  };

  let roman = "";
  let decimal = Object.keys(numerals);
  decimal.forEach(key => {
    while(key <= num){
      roman += numerals[key];
      num -= key;
    };
  });
  
  return roman; // Return the Roman numeral string
};
convertToRoman(4);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36

Challenge Information:

JavaScript Algorithms and Data Structures Projects - Roman Numeral Converter

Yes, if you tried to log what your function returns with any number you will see that it returns multiple Is:

console.log(convertToRoman(2));       // II
console.log(convertToRoman(5));       // IIIII
console.log(convertToRoman(10));      // IIIIIIIIII

Your declaration of the numerals object is correct ( BiggestSmallest ).

BUT, if you tried to log your decimal array you will see this:

[ '1',
  '4',
  '5',
  '9',
  '10',
  '40',
  '50',
  '90',
  '100',
  '400',
  '500',
  '900',
  '1000' ]

As you see, it’s not in the desired order for it to work. That’s because Object.keys() orders them in ascending order.

Try reversing it and see if it works.

It worked. Thanks for helping.

1 Like