Roman Numeral Converter recursive solution

Hey guys!

Check this recursive function solution for the Roman numeral converter. For some reason I don’t pass any of the tests. Why could it be?

let numbersRoman = {
   '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
 }
const numbersArabic = Object.values(numbersRoman)

function getKeyByValue(object, value) {
  return Object.keys(object).find(key => object[key] === value);
}
let res = ''
function convertToRoman(num) {
  let modArr = numbersArabic.map(val => num%val)
  let check = modArr.findIndex(v => v!== num)
  let filtered = modArr.filter(v => v!==num)
  if(filtered.length!==0){
    for(let i = 0; i < Math.floor(num/numbersArabic[check]); i++){
      res = res + getKeyByValue(numbersRoman, numbersArabic[check])
    }
    convertToRoman(filtered[0])
  }
  return res
  
}

console.log(convertToRoman(4600))

Thank you in advance for your help!

Your use of a global variable instead of using the return value of the recursive function call is breaking your logic. Using a global variable like this means your function is no longer reusable.

I would ditch the global variable and instead use the return value from the recursive call in your function.

Thank you! I’ll check that

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.