function convertToRoman(num) {
//seperate the number in to singular digits which are strings and pass to array.
var array = ("" + num).split(""),
arrayLength = array.length,
romStr = "";
//Convert the strings in the array to numbers
array = array.map(Number);
//Itterate over every number in the array
for (var i = 0; i < array.length; i++) {
//Calculate what power of ten the digit is by minusing it's index from the array length and passing it to variable "tenToPowerOf"
var tenToPowerOf = arrayLength - array.indexOf(array[i]) - 1,
low = "",
mid = "",
upp = "";
//Set the low, mid and high variables based on their tenToPowerOf value
switch (tenToPowerOf) {
case 0:
low = "I";
mid = "V";
upp = "X";
break;
case 1:
low = "X";
mid = "L";
upp = "C";
break;
case 2:
low = "C";
mid = "D";
upp = "M";
break;
case 3:
low = "M";
mid = "¯V";
upp = "¯X";
break;
}
//Check for digit value and add it's Roman Numeral value (based on it's power from the above switch statement) to romStr
//The problem is, switch "remembers" the value of low, mid and high from the last time it itterated over the number. Thus 99 becomes "XCXC" and not "XCIX".
switch (array[i]) {
case 1:
romStr += low;
break;
case 2:
romStr += low.repeat(2);
break;
case 3:
romStr += low.repeat(3);
break;
case 4:
romStr += low + mid;
break;
case 5:
romStr += mid;
break;
case 6:
romStr += mid + low;
break;
case 7:
romStr += mid + low.repeat(2);
break;
case 8:
romStr += mid + low.repeat(3);
break;
case 9:
romStr += low + upp;
break;
case 10:
romStr += upp;
break;
default:
break;
}
}
//return array;
return romStr;
}
convertToRoman(99);
- Yes, I have spent my share share of time looking for a relevant answer before asking (1.5+ hours).
The function converts numbers in to Roman Numerals.
- It takes a number argument passed to it
- Splits the number in to digits
- Converts then in to an array
- Then based on the number's power of ten (or position relevant to the length of the number) sets the low mid and high values
- These values are then applied in the order dictated by Roman Numerals and pushed to a string
- Finally, the string is returned.
It works with numbers that have digits occurring no more than once. The reason for this is because when the switch case is matched more than once in the for loop, it applies the low, mid and high values from the previous iteration.
- The question is in the title but I would also like to ask for a solution to the problem that I am trying to solve please.
- I will gladly provide more information and will answer every question