Last active
September 29, 2016 08:40
-
-
Save edgarberm/93af9b15938b12ce011afa0e084860d5 to your computer and use it in GitHub Desktop.
Converts a number to a Roman numeral string
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 roman = (n) => { | |
n = String(Math.floor(Math.abs(n))) | |
let element, i, result = '' | |
const table = [ | |
['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'], | |
['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'], | |
['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'] | |
] | |
for (i = 0; i < table.length; i += 1) { | |
element = table[i][n.slice(-1)] | |
if (element) { | |
result = element + result | |
} | |
n = n.slice(0, -1) | |
} | |
return 'M'.repeat(+n) + result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment