Skip to content

Instantly share code, notes, and snippets.

@edgarberm
Last active September 29, 2016 08:40
Show Gist options
  • Save edgarberm/93af9b15938b12ce011afa0e084860d5 to your computer and use it in GitHub Desktop.
Save edgarberm/93af9b15938b12ce011afa0e084860d5 to your computer and use it in GitHub Desktop.
Converts a number to a Roman numeral string
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