Files
  • index.js
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
const MDCCLXXVI = 'MDCCLXXVI'; // 1776
const MCMLIV = 'MCMLIV'; // 1954
const MCMXC = 'MCMXC'; // 1990

function toDecimal(numeral) {
  const troublesomeGlyphs = {
    "iv": "ⅳ", // 4
    "ix": "ⅸ", // 9
    "xl": "f", // 40
    "xc": "n", // 90
    "cd": "F", // 400
    "cm": "N", // 900
  };

  const sym = {
    "i": 1,
    "ⅳ": 4,
    "v": 5,
    "ⅸ": 9,
    "x": 10,
    "l": 50,
    "f": 40,
    "n": 90,
    "c": 100,
    "F": 400,
    "d": 500,
    "N": 900,
    "m": 1000,
  };
  numeral = numeral.toLowerCase();
  (Object.keys(troublesomeGlyphs)).forEach(k => {
    numeral = numeral.replace(k, troublesomeGlyphs[k]);
  });
  return numeral
    .split('')
    .map(n => sym[n])
    .reduce((total, current) => total + current, 0);
}

console.log(toDecimal('IV'));
console.log(toDecimal('VIII'));
console.log(toDecimal('IX'));
console.log(toDecimal('XL'));
console.log(toDecimal('XC'));
console.log(toDecimal(MDCCLXXVI));
console.log(toDecimal(MCMLIV));
console.log(toDecimal('MCMLXXIV'));
console.log(toDecimal(MCMXC));
console.log(toDecimal('MCMXCIV'));
node v9.7.1 linux/amd64