Can anyone suggest ways to improve this code?
function convertToRoman(num) {
let one = ["M", "C", "X", "I"] // [1000, 100, 10, 1]
let six = [0, "DC", "LX", "VI"] // [6000, 600, 60, 6]
var romanNumerals = {
// Each value contains a list with the roman numerals in the Thousands, Hundreds, Tens, Ones order
// for that number
"0": ["", "", "", ""], // Default value 0 stores empty string
"1": one,
"2": one.map(i => i += i[i.length -1]), //Adds repeated value (M, C, X, I) [2000, 200, 20, 2]
"3": one.map(i => i += i[i.length -1].repeat(2)),
// Adds repeated value twice(M, X, C, I) [3000, 300, 30, 3]
// Number at thousands place not greater than 3 so we default the thousands place value to 0 for >3
"4": [0, "CD", "XL", "IV"], // [0, 400, 40, 4]
"5": [0, "D", "L", "V"], // [0, 500, 50, 5]
"6": six,
"7": six.map(i => { // Adds repeated value (C, X, I) to respective elements
if (typeof(i) !== "number") i+= i[i.length -1] // Skips over 0 in loop and adds repeated value
return i
}), // [0, 700, 70, 7]
"8": six.map(i => { // Adds repeated value (C, X, I) twice to respective elements
if (typeof(i) !== "number") i+= i[i.length -1].repeat(2) //Skips over 0 in loop and adds value
return i
}), // [0, 800, 80, 8]
"9": [0, "CM", "XC", "IX"] // [0, 900, 90, 9]
}
num += ""
while (num.length < 4) // Adds 0 in the beginning of number to make sure it is 4 digits
num = "0" + num
let romanNum = ''
for (let i = 0; i < num.length; i++) {
romanNum += romanNumerals[num[i]][i]
// num[i] stores the digit at that place
// i stores the digits place in (Thousands, Hundreds, Tens, Ones)
// i corresponds to the index number in the list for the key num[i]
}
console.log(romanNum)
return romanNum;
}
convertToRoman(1984);