Skip to content

Instantly share code, notes, and snippets.

@behcet
Created October 23, 2018 18:13
Show Gist options
  • Save behcet/179086dd2073e99fe85f33ccb45ea6a2 to your computer and use it in GitHub Desktop.
Save behcet/179086dd2073e99fe85f33ccb45ea6a2 to your computer and use it in GitHub Desktop.
const ROMAN_MAP = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
};
const ARABIC_MAP = new Map([
[ 1000, 'M' ],
[ 900, 'CM' ],
[ 500, 'D' ],
[ 400, 'CD' ],
[ 100, 'C' ],
[ 90, 'XC' ],
[ 50, 'L' ],
[ 40, 'XL' ],
[ 10, 'X' ],
[ 9, 'IX' ],
[ 5, 'V' ],
[ 4, 'IV' ],
[ 1, 'I' ]
]);
function toArabic (numberString) {
numberString = numberString.split('').map(digit => digit.toUpperCase());
return numberString.reduce((tally, digit, i) => {
const nextDigit = ROMAN_MAP[numberString[i + 1]];
digit = ROMAN_MAP[digit];
if (nextDigit > digit) {
tally = tally - digit;
} else {
tally = tally + digit;
}
return tally;
}, 0);
}
function toRoman (integer) {
let romanString = '';
let remainder = integer;
ARABIC_MAP
.forEach((romanLetter, decimalValue) => {
const count = parseInt(remainder / decimalValue, 10);
if (count > 0) {
romanString = romanString.split('').concat(Array(count).fill(romanLetter)).join('');
remainder = remainder - (decimalValue * count);
}
}, integer);
return romanString;
}
console.log(toArabic('MCMV'));
console.log(toRoman(1905));
console.log(toRoman(8));
console.log(toRoman(328));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment