Hello @all, this is my solution, with comments.
I think could be good for newbies because there's not too much logic and it's a step by step process.
I hope i posted in the right place.
function convertToRoman(num) {
/* convert the number to a string and split it in elements that will be stored in splittedNum array */
let splittedNum = num.toString().split("");
// create arrays for roman numbers entities
let romanMig = [], romanCents = [], romanDecine = [], romanUnits = [];
romanUnits = [ "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"];
romanDecine = ["X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", "C" ]
romanCents = ["C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", "M"];
romanMig = ["M", "MM", "MMM", "MMMM", "MMMMM", "MMMMMM", "MMMMMMM", "MMMMMMMM","MMMMMMMMM", "MMMMMMMMMM" ];
/* the functions below first extracts the value of the unit (dec , cent, migliaia) from the relative index of the splitted number (array.length - 1 for units, - 2 for dec, - 3 for cents, - 4 for migliaia).
For example we extract the unit "6" from "36".
Then we use the number 6 to extract the corresponding roman number (VI) from the array romanUnits [].
Using 6 as index-1 ( because the array index starts from 0) in the array romanUnits we got romanUnits[5] and we etract the corresponding element at index 5 > that is VI
In fact index 0 = "I", index 1 = "II", index 2 = "III", index 3 = "IV", index 4 = "V", index 5 = "VI", etc...).
Same approach with decine (position in the number is at array.length -2 (in the example with the number 36 we extract 3 from the splittedNum ["3", "6"] ),
Then set the code for doing the same with cent (position at -3) and migliaia (position at -4) in case of bigger number provided to the functions.
*/
const findRomanUnit = arr => arr[splittedNum[(splittedNum.length - 1)] -1 ];
const findRomanDecina = arr => arr[splittedNum[(splittedNum.length - 2)] - 1];
const findRomanCents = arr => arr[splittedNum[(splittedNum.length - 3)] - 1]
const findRomanMig = arr => arr[splittedNum[(splittedNum.length - 4)]- 1];
// synthetize the above code
const migliaia = findRomanMig(romanMig);
const cen = findRomanCents(romanCents);
const dec = findRomanDecina(romanDecine);
const un = findRomanUnit(romanUnits);
// we build our array model for the roman number, based on position of the values
let romanNum = [migliaia, cen, dec, un];
/* now we create a function to eliminate elements that throw undefined from our array, for example numbers like 2014, having a zero inside, can throw undefined for the cents
*/
function eliminaUndef (arr) {
let newArr = arr.filter(el => el !== undefined);
return newArr.join("").toString();
}
let result = eliminaUndef(romanNum);
return result;
}
convertToRoman(36);
Hope it helps, Bye