Skip to content

Instantly share code, notes, and snippets.

@gkucmierz
Created October 29, 2016 02:38
Show Gist options
  • Select an option

  • Save gkucmierz/29cb33af637be58d9983dabfd5b9708b to your computer and use it in GitHub Desktop.

Select an option

Save gkucmierz/29cb33af637be58d9983dabfd5b9708b to your computer and use it in GitHub Desktop.
Roman Numerals Converter
let RomanNumerals = {
toRoman: (n) => {
let m = [
['I', 'V'],
['X', 'L'],
['C', 'D'],
['M']
];
let c = ' 0 00 000 01 1 10 100 1000 02'.split(' ');
let res = [];
let i = 0;
while (n > 0) {
let t = n % 10;
res.unshift(c[t].split('').map((e) => {
if (+e === 2) return m[i+1][0];
return m[i][e];
}).join(''));
++i;
n = (n - t) * 0.1;;
}
return res.join('');
},
fromRoman: (s) => {
let m = {
'I': 1, 'V': 5,
'X': 10, 'L': 50,
'C': 100, 'D': 500,
'M':1000
};
return s.split('').reduce((a, c, i) => {
let curr = m[c];
let last = a.slice(-1)[0];
if (last > curr || i === 0) {
a.push(curr);
} else if (last < curr) {
a.push(-a.pop());
a.push(curr);
} else {
a.push(a.pop() + curr);
}
return a;
}, []).reduce((acc, n) => acc + n);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment