I've created a simple function that is supposed to translate a number into a Roman Numeral. It appears that everything is working properly except one thing.
Through every recursion in my code, the string that holds the roman numerals is reset to "".
What is the best practice for maintaining variables like this through recursions in a function?
I tried declaring variable romanStr = "" in the global scope, and removing the conditional declaration within the program, and of course that worked. I however know that is the worst practice.
For example, take the number 1234, which converted into roman numerals is "MCCXXXIV". My program will only return "IV", the result of the last recursion.
function convertToRoman(num) {
console.log(`START FUNCTION FROM THE BEGINNING`);
console.log(`current num: ${num}`);
if (typeof romanStr === "undefined") {
var romanStr = "";
}
const bNumbers = [1000, 500, 100, 50, 10, 5, 1];
const romanSymbols = {
0: ["M"],
2: ["C", "D", "M"],
4: ["X", "L", "C"],
6: ["I", "V", "X"]
};
const arraySelector = arrNum => num >= arrNum;
let symbolSetIndex = bNumbers.findIndex(arraySelector);
console.log(`symbolSetIndex: ${symbolSetIndex}`);
let symbolSet = romanSymbols[symbolSetIndex];
console.log(`symbolSet: [${symbolSet}]`);
let numString = num.toString();
let numeral = parseInt(numString[0]);
console.log(`numeral: ${numeral}`);
let nextNum = parseInt(numString.substr(1));
console.log(`nextNum: ${nextNum}`);
// CONDITIONAL STATEMENTS //
if (symbolSetIndex === 0) {
for (let i = 1; i <= numeral; i++) {
romanStr = `${romanStr}${symbolSet[0]}`;
}
return convertToRoman(nextNum);
}
if (numeral < 4) {
for (let i = 1; i <= numeral; i++) {
romanStr = `${romanStr}${symbolSet[0]}`;
}
}
if (numeral === 4) {
romanStr = `${romanStr}${symbolSet[0]}${symbolSet[1]}`;
}
if (numeral === 5) {
romanStr = `${romanStr}${symbolSet[1]}`;
}
if (numeral === 6) {
romanStr = `${romanStr}${symbolSet[1]}${symbolSet[0]}`;
}
if (numeral > 6) {
romanStr = `${romanStr}${symbolSet[1]}`; // requires the 5 numeral first
for (let i = 1; i <= numeral - 6; i++) {
romanStr = `${romanStr}${symbolSet[0]}`;
}
}
if (numeral === 9) {
romanStr = `${romanStr}${symbolSet[2]}${symbolSet[1]}`;
}
if (numString.length === 1) {
return romanStr;
}
return convertToRoman(nextNum);
}
console.log(convertToRoman(5214));