Advertisement
ibarmin

Roman dates

Jan 28th, 2020
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function toRoman(date)
  2. {
  3.     const thousands = Math.floor(date / 1000);
  4.     date %= 1000;
  5.     const hundreds = Math.floor(date / 100);
  6.     date %= 100;
  7.     const tenths = Math.floor(date / 10);
  8.     const singles = date % 10;
  9.     const convert = function (digit, single, five, next) {
  10.         if (digit == 0) {
  11.             return '';
  12.         }
  13.         return digit == 9 ? single + next : digit == 4 ? single + five :  ((digit > 4 ? five : '') + single.repeat(digit % 5));
  14.     }
  15.  
  16.     let result = '';
  17.     if (thousands > 0) {
  18.         result += 'M'.repeat(thousands);
  19.     }
  20.     result += convert(hundreds, 'C', 'D', 'M');
  21.     result += convert(tenths, 'X', 'L', 'C');
  22.     result += convert(singles, 'I', 'V', 'X');
  23.    
  24.     return result;
  25. }
  26.  
  27. function fromRoman(date)
  28. {
  29.     const cost = {
  30.         'I': 1,
  31.         'V': 5,
  32.         'X': 10,
  33.         'L': 50,
  34.         'C': 100,
  35.         'D': 500,
  36.         'M': 1000
  37.     };
  38.     return date.toUpperCase().split('').reduce(function (accumulator, el, i, letters) {
  39.         if (typeof cost[el] == "undefined") {
  40.             return accumulator;
  41.         }
  42.         if (
  43.             el == 'I' && 'VX'.indexOf(letters[i+1]) != - 1
  44.             || el == 'X' && 'LC'.indexOf(letters[i+1]) != - 1
  45.             || el == 'C' && 'DM'.indexOf(letters[i+1]) != - 1
  46.         ) {
  47.             return accumulator - cost[el];
  48.         }
  49.         return accumulator + cost[el];
  50.     }, 0);
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement