Roman numeral converter - recursion problem

Roman numeral converter - recursion problem
0

#1

Hi guys.
I tried to write roman numeral converter using recursion, as I spent some time trying to understand it… However, it turns out I still don’t understand it. I tried to follow the function line by line, but I don’t get why the function doesn’t stop after num === 0, but it makes num === 2 and executes it until again num === 0, then stops. Can anyone help?

function convertToRoman(num) {
 var newNum = "";
 var arabNums = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ];
  var romanNums = [ 'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I' ];
  for (var i = 0; i < arabNums.length; i++) {
    if (num >= arabNums[i]) {
      newNum += romanNums[i];
      num -= arabNums[i];
      console.log(num);
      convertToRoman(num);
    }
  }
  return newNum;
}

#2

Generally, you want to be using recursion or loops, not both - but putting that aside.
This line convertToRoman(num); is not really doing anything. convertToRoman() returns a value, but your code does not do anything with that value, so calling the function recursively has no effect.

Another issue is that you are not exiting your loop in the body of your if block. Since you are changing the value of num in your ifblock, it is possible to to satisfy the condition more than once. This would give you incorrect results.

Spoiler: here is a working solution with the minimum of changes to your code
function convertToRoman(num) {
 var newNum = "";
 var arabNums = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ];
  var romanNums = [ 'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I' ];
  for (var i = 0; i < arabNums.length; i++) {
    if (num >= arabNums[i]) {
      newNum += romanNums[i];
      num -= arabNums[i];
      return newNum + convertToRoman(num);
    }
  }
  return newNum;
}