JavaScript program to convert positive integers to roman numbers

We are required to write a JavaScript function that takes in a positive roman number and returns its roman representation.

The following values we will use to set roman numbers for positive integers −

const legend = { 1: 'I', 2: 'II', 3: 'III', 4: 'IV', 5: 'V', 6: 'VI', 7:
'VII', 8: 'VIII', 9: 'IX', 10: 'X', 20: 'XX', 30: 'XXX', 40: 'XL', 50:
'L', 60: 'LX', 70: 'LXX', 80: 'LXXX', 90: 'XC', 100: 'C', 200: 'CC', 300:
'CCC', 400: 'CD', 500: 'D', 600: 'DC', 700: 'DCC', 800: 'DCCC', 900: 'CM',
1000: 'M', 2000: 'MM', 3000: 'MMM', 4000: 'MMMM', 5000: 'MMMMM', 6000:
'MMMMMM', 7000: 'MMMMMMM', 8000: 'MMMMMMMM', 9000: 'MMMMMMMMM' };

Example

The code to convert positive integers to roman numbers is as follows −

const decimalToRoman = (num = 1) => {
const legend = { 1: 'I', 2: 'II', 3: 'III', 4: 'IV', 5: 'V', 6: 'VI',
7: 'VII', 8: 'VIII', 9: 'IX', 10: 'X', 20: 'XX', 30: 'XXX', 40: 'XL', 50:
'L', 60: 'LX', 70: 'LXX', 80: 'LXXX', 90: 'XC', 100: 'C', 200: 'CC', 300:
'CCC', 400: 'CD', 500: 'D', 600: 'DC', 700: 'DCC', 800: 'DCCC', 900: 'CM',
1000: 'M', 2000: 'MM', 3000: 'MMM', 4000: 'MMMM', 5000: 'MMMMM', 6000:
'MMMMMM', 7000: 'MMMMMMM', 8000: 'MMMMMMMM', 9000: 'MMMMMMMMM' };
const arr = num.toString().split("").reverse();
let i = 1, k;
for (k = 0; k < arr.length; k++) {
arr.splice(k, 1, arr[k] * i);
i *= 10;
};
const romansArray = [];
for (i = 0; i < arr.length; i++) {
romansArray.push(legend[arr[i]]||'');
}
return romansArray.reverse().join("");
}
console.log(decimalToRoman(345));

Output

And the output in the console will be −/p>

CCCXLV