-1

I have been trying to convert roman numbers to integers but not able to figure out the errors in my code. It is showing this error RangeError: Invalid array length. Could anybody help me . Thanks in advance.

function convertToRoman(num) {
  var arr = {'1':'I','5':"V",'10':"X",'50':"L",'100':"C",'500':"D",'1000':"M"} ;
  var result = "";
  var mult = 1;
  while ( num % 10 !== 0) {
    var n = num % 10 ;
    var h = n*mult;
    if( n < 4 ) {
      //console.log("eroor1-");
      result = Array(n+1).join(arr[h.toString()]) + result;
    }
    else if (n == 4) {
      //console.log("eroor2-");
      result = arr[(h-mult).toString()] + arr[h.toString()] + result;
    }
    else if(n == 5) {
      //console.log("eroor3-");
      result = arr[h.toString()] + result;
    }
    else if( n < 9 ) {
      //console.log("eroor4-");
      result = Array(n-4).join(arr[mult.toString()]) + result;
      //console.log("eroor4.1-");
      result = arr[h.toString()] + result;
    }
    else if(n == 9) {
     // console.log("eroor5-");
      result = arr[(h+mult).toString()] + arr[h.toString()] + result;
    }
    else {
      result = arr[h.toString()] + result;
    }

    mult *= 10;
    num = num / 10;
  }
 return result;
}

convertToRoman(36);
random
  • 3
  • 2

1 Answers1

0

Your variable arr is an object and not an array. In order to take the next step in troubleshooting your code, you should either change it to an array or utilize it as an object

Corbfon
  • 3,514
  • 1
  • 13
  • 24