Roman numerals as values, not pass the input-output test at freecodecamp.com for converting decimal numbers to Roman numerals.
Why does the first code below, where the decimal numbers are used as keys and the Roman numerals as values, not pass the input-output test at freecodecamp.com for converting decimal numbers to Roman numerals? However, the second code, where the keys and values have switched places, does pass the test. The only difference between the two codes is the ordering of the keys and values in the romanNumerals object.
Why does this seemingly simple change affect the test results?
The first code for converting decimal numbers to Roman numerals only work correctly for the inputs convertToRoman(2) and convertToRoman(3), but fails for other input numbers such as 4, 5, 9, 12, 16, etc.? Despite seemingly correct logic and loop iterations, it produces incorrect results for various input values.
What could be causing this issue specifically for the mentioned input numbers, and how can it be resolved?
1.
function convertToRoman(num) {
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"
};
let roman = "";
let restartLoop = false;
do {
restartLoop = false;
for (let key in romanNumerals) {
if (num >= key) {
roman += romanNumerals[key];
num -= key;
restartLoop = true;
break;
}
}
} while (restartLoop);
return roman;
}
console.log(convertToRoman(3))
console.log(convertToRoman(4))
console.log(convertToRoman(23))
2.
function convertToRoman(num) {
const romanNumerals = {
"M": 1000,
"CM": 900,
"D": 500,
"CD": 400,
"C": 100,
"XC": 90,
"L": 50,
"XL": 40,
"X": 10,
"IX": 9,
"V": 5,
"IV": 4,
"I": 1
};
let roman = "";
let restartLoop = false;
do {
restartLoop = false;
for (let key in romanNumerals) {
if (num >= romanNumerals[key]) {
roman += key;
num -= romanNumerals[key];
restartLoop = true;
break;
}
}
} while (restartLoop);
return roman;
}
console.log(convertToRoman(3))
console.log(convertToRoman(4))
console.log(convertToRoman(23))