Hey guys!
I finished my Roman Numeral Converter and after looking through the solutions to compare, I found that mine isn’t quite as concise as some of them, so I’m just looking for some feedback
My solution seems longer than the others but actually without comments etc it’s only 19 lines and, seeing as I’ve been coding only since the beginning of November, I don’t really have an idea if my code is clunky, verbose or hard to follow or anything. With that, if anyone has any pointers for me to improve then I’d really appreciate it!
Code below (working solution: SPOILER BELOW!)
//Split num into workable integers in an array and reverse to facilitate counting
let newNum = num.toString().slice().split("").reverse();
//Create required variables: Roman values, position counters, newNum/results array
let curr = "", mid = "", next = "", posit = 0, result = [];
let numerals = ["I", "V", "X", "L", "C", "D", "M"];
//Function to take each integer and return Roman equivalent using shifting variables which depend on integer's position in num array
let convert = (num) => {
let index = {
"0": "",
"1": curr,
"2": curr.repeat(2),
"3": curr.repeat(3),
"4": curr + mid,
"5": mid,
"6": mid + curr,
"7": mid + curr.repeat(2),
"8": mid + curr.repeat(3),
"9": curr + next
}
return index[num];
}
//Cycle through num array, altering which Roman numerals will be used for each integer
for (let i = 0; i < newNum.length; i++) {
curr = numerals[posit];
mid = numerals[posit + 1];
next = numerals[posit + 2];
//Convert digit to Roman numeral and continue to next digit and Roman value set
result.unshift(convert(newNum[i]));
posit += 2;
}
//Finally, join number array into a string
return result.join("");
}
console.log(convertToRoman(2018));```