Guest User

Untitled

a guest
Oct 23rd, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. const ROMAN_MAP = {
  2. 'I': 1,
  3. 'V': 5,
  4. 'X': 10,
  5. 'L': 50,
  6. 'C': 100,
  7. 'D': 500,
  8. 'M': 1000
  9. };
  10.  
  11. const ARABIC_MAP = new Map([
  12. [ 1000, 'M' ],
  13. [ 900, 'CM' ],
  14. [ 500, 'D' ],
  15. [ 400, 'CD' ],
  16. [ 100, 'C' ],
  17. [ 90, 'XC' ],
  18. [ 50, 'L' ],
  19. [ 40, 'XL' ],
  20. [ 10, 'X' ],
  21. [ 9, 'IX' ],
  22. [ 5, 'V' ],
  23. [ 4, 'IV' ],
  24. [ 1, 'I' ]
  25. ]);
  26.  
  27. function toArabic (numberString) {
  28. numberString = numberString.split('').map(digit => digit.toUpperCase());
  29. return numberString.reduce((tally, digit, i) => {
  30. const nextDigit = ROMAN_MAP[numberString[i + 1]];
  31. digit = ROMAN_MAP[digit];
  32. if (nextDigit > digit) {
  33. tally = tally - digit;
  34. } else {
  35. tally = tally + digit;
  36. }
  37. return tally;
  38. }, 0);
  39. }
  40.  
  41. function toRoman (integer) {
  42. let romanString = '';
  43. let remainder = integer;
  44. ARABIC_MAP
  45. .forEach((romanLetter, decimalValue) => {
  46. const count = parseInt(remainder / decimalValue, 10);
  47. if (count > 0) {
  48. romanString = romanString.split('').concat(Array(count).fill(romanLetter)).join('');
  49. remainder = remainder - (decimalValue * count);
  50. }
  51. }, integer);
  52. return romanString;
  53. }
  54.  
  55. console.log(toArabic('MCMV'));
  56. console.log(toRoman(1905));
  57. console.log(toRoman(8));
  58. console.log(toRoman(328));
Add Comment
Please, Sign In to add comment