Help needed on Roman Numeral converter

I’m trying to do my javascript project which converts the given number into Roman numeral.

This is my code

 function convertToRoman(num) {
    var rom = { 2: 'II', 3: 'III', 4: 'IV', 5: 'V', 9: 'IX', 12: 'XII', 16: 'XVI', 29: 'XXIX', 36: 'XXXVI', 44: 'XLIV', 68: 'LXVIII', 83: 'LXXXIII', 97: 'XCVII', 99: 'XCIX', 400: 'CD', 500: 'D', 501: 'DI', 649: 'DCXLIX', 798: 'DCCXCVIII', 891: 'DCCCXCI', 1000: 'M', 1004: 'MIV', 1006: 'MVI', 1023: 'MXIII', 2014: 'MMXIV', 3999: 'MMMCMXCIX'   };
    num = Object.values(rom);
 return num;
}

I’m trying to return the values of the object this way so that the Roman numerals would return. But all the conditions were showing wrong in the output . Please help.

First of all, read what Object.values does. It returns an array of all the values in an object, eg:

const obj = { foo: 'bar', baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]

So you’re just returning

[
  "II",
  "III",
  "IV",
  "V",
  "IX",
  "XII",
  "XVI",
  "XXIX",
  "XXXVI",
  "XLIV",
  "LXVIII",
  "LXXXIII",
  "XCVII",
  "XCIX",
  "CD",
  "D",
  "DI",
  "DCXLIX",
  "DCCXCVIII",
  "DCCCXCI",
  "M",
  "MIV",
  "MVI",
  "MXIII",
  "MMXIV",
  "MMMCMXCIX"
]

Every time. You’re also overwriting the argument with that every time for some reason.

I assume you meant to write:

 function convertToRoman(num) {
   var rom = { 2: 'II', 3: 'III', 4: 'IV', 5: 'V', 9: 'IX', 12: 'XII', 16: 'XVI', 29: 'XXIX', 36: 'XXXVI', 44: 'XLIV', 68: 'LXVIII', 83: 'LXXXIII', 97: 'XCVII', 99: 'XCIX', 400: 'CD', 500: 'D', 501: 'DI', 649: 'DCXLIX', 798: 'DCCXCVIII', 891: 'DCCCXCI', 1000: 'M', 1004: 'MIV', 1006: 'MVI', 1023: 'MXIII', 2014: 'MMXIV', 3999: 'MMMCMXCIX'   };

   return rom[num];
}

Second thing, and the critical thing here, is that you aren’t really programming anything, you’re missing the point. If you change to the above, the function will pass the tests, but it’s useless, because:

What’s the value of this?

convertToRoman(1)

What’s the value of this?

convertToRoman(6)

Or this?

convertToRoman(62)

All you’re doing is writing the answers to the tests. Which are just tests, they are supposed to give you confidence your code works, they aren’t just a thing you copy the values to.

The point is to program the function so that it converts any number (well, any positive integer up to 4000) to a roman numeral.

1 Like

@DanCouper Thank you for correcting my mistake. Yes, it’s not actually programming. I would find another way to do this solution and convert the numbers into numerals.