DEV Community

Discussion on: Roman Numeral Converter

Collapse
 
itsasine profile image
ItsASine (Kayla)
function solution(number){
  // todo: solve without defining middle values :(
  var translations = {
    '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
  };
  var answer = '';
  var value = 0;
  var thisPower = 0;

  Object.keys(translations).forEach(function(letter, index, array) {
    thisPower = translations[letter];
    value = Math.floor(number / thisPower);

    number -= value * thisPower;
    answer += letter.repeat(value);
  });

  return answer;
}

Mine works... but I every time I tried doing something clever to not have to define 900, 400, 90, 40, and 9, it wouldn't work on 4, so I gave up on that. I really liked the .repeat so I didn't have to define multiples, though.