Created
May 8, 2018 00:46
-
-
Save mwakipesile/5cb02b33e905a2ef7d103204d00ad536 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 | |
if (!validInput(num)) return 'Invalid input'; | |
digits = num.toString().split(''); | |
last_idx = digits.length - 1; | |
function validInput(num) { | |
var digits = num => num.split('').every(chr => chr >= '0' && chr <= '9'); | |
if (typeof num === 'string' && digits(num)) num = Number(num); | |
if (Number.isInteger(num)) return num > 0 && num <= 3000; | |
return false; | |
} | |
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