Feedback on JavaScript Roman Numerals

Hello,

I’ve recently completed the Roman Numeral challenge in the JavaScript section after taking a little bit of a break from FreeCodeCamp.

There are a few things I’m not sure I’ve done right, or feel that they could be improved upon.

  • Do I have too many functions for this task?
  • Is there a better way to handle 4?
  • Is there a better way to call the different functions based on position rather than switch?
function convertToRoman(num) {

  let str = ""; 
  let digits = String(num).split("");

  let count = 0;
  for (let digit of digits.reverse()) {
    switch (count){
      case 0: 
        str = units(digit) + str;
        break; 
      case 1: 
        str = tens(digit) + str; 
        break;
      case 2: 
        str = hundreds(digit) + str; 
        break; 
      case 3:
        str = thousands(digit) + str; 
        break; 
      default:
        return console.log(`Function not available - ${num} is too large.`); 

    }

    count++;
  }

  
  // console.log(str)
  return str; 
}

function rangeRomans(num, lower, mid, upper){
  if (num <= 3) {
    return lower.repeat(num); 
  } else if (num <= 8) { 
      if (num == 4 ) {
        return lower + mid; 
      } else {
        return mid + lower.repeat(num-5); 
      }
  } else {
    return lower + upper; 
  }
}

function thousands(num) {
  return rangeRomans(num, "M", "(V)", "(X)"); 
}

function hundreds(num) {
  return rangeRomans(num, "C", "D", "M");
}

function tens(num) {
  return rangeRomans(num, "X", "L", "C");
}

function units(num) { 
  return rangeRomans(num, "I", "V", "X"); 
}

Thanks,
C :slight_smile:

@craigdavison2707, I’m moving your topic to the #javascript subforum here it will get more view.
I’ve also surrounded your code with [spoiler] [/spoiler] tags for those that have not seen this project yet.

1 Like