Last active
May 8, 2018 00:32
-
-
Save mwakipesile/50b88d1406528700c265c6356f6eb68c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const RomanDictionary = { | |
'1': 'I', | |
'5': 'V', | |
'10': 'X', | |
'50': 'L', | |
'100': 'C', | |
'500': 'D', | |
'1000': 'M', | |
}; | |
function toRoman(num) { | |
var digits; | |
var last_idx | |
digits = num.toString().split(''); | |
last_idx = digits.length - 1; | |
function toRomanNumeral(digit, idx) { | |
var place_val = 10 **(last_idx - idx); | |
var toRomanSym = num => RomanDictionary[num.toString()]; | |
digit = Number(digit); | |
if (digit === 0) return ''; | |
if (digit < 4) return toRomanSym(place_val).repeat(digit); | |
if (digit === 4 || digit === 9) { | |
return toRomanSym(place_val) + toRomanSym((digit + 1) * place_val); | |
} | |
// Default: for digits 6 to 8 | |
return toRomanSym(5 * place_val) + toRomanSym(place_val).repeat(digit - 5); | |
} | |
return digits.map(toRomanNumeral).join(''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment