Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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));
Add Comment
Please, Sign In to add comment