Skip to content

Instantly share code, notes, and snippets.

@hsingtism
Created June 1, 2024 02:55
Show Gist options
  • Select an option

  • Save hsingtism/76ab60eb92ced189cfb9b41d66ecf75c to your computer and use it in GitHub Desktop.

Select an option

Save hsingtism/76ab60eb92ced189cfb9b41d66ecf75c to your computer and use it in GitHub Desktop.
const digitKey = [
"","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",
"","M","MM","MMM"
]
const arabicToRoman = n => n.toString().padStart(4, '0').split('').map((v, i) => digitKey[+v + (3 - i) * 10]).join('')
arabicToRoman.validate = n => Number.isInteger(n) && n > 0 && n < 4000
const letterKey = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
const romanToArabic = s => s.split('')
.reduce((acc, val, i, arr) => letterKey[arr[i+1]] > letterKey[val] ? acc - letterKey[val] : acc + letterKey[val], 0)
romanToArabic.validate = s => /^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/.test(s) && !!s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment