Files
30-seconds-of-code/snippets/js/s/to-roman-numeral.md
2023-05-07 16:07:29 +03:00

1.1 KiB

title, type, language, tags, cover, dateModified
title type language tags cover dateModified
Integer to roman numeral snippet javascript
math
string
ancient-greek-building 2020-10-22T20:24:44+03:00

Converts an integer to its roman numeral representation. Accepts value between 1 and 3999 (both inclusive).

  • Create a lookup table containing 2-value arrays in the form of (roman value, integer).
  • Use Array.prototype.reduce() to loop over the values in lookup and repeatedly divide num by the value.
  • Use String.prototype.repeat() to add the roman numeral representation to the accumulator.
const toRomanNumeral = num => {
  const lookup = [
    ['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],
  ];
  return lookup.reduce((acc, [k, v]) => {
    acc += k.repeat(Math.floor(num / v));
    num = num % v;
    return acc;
  }, '');
};
toRomanNumeral(3); // 'III'
toRomanNumeral(11); // 'XI'
toRomanNumeral(1998); // 'MCMXCVIII'