Skip to content

Instantly share code, notes, and snippets.

@granmoe
Created February 6, 2019 02:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save granmoe/454bd4502c24591ea6fb45f624b2ff3a to your computer and use it in GitHub Desktop.
Save granmoe/454bd4502c24591ea6fb45f624b2ff3a to your computer and use it in GitHub Desktop.
Convert an integer of 9,999 or less to a roman numeral with JS (just a terrible JS interview question that got stuck in my head)
const convertToRomanNumerals = int => {
const romanNumerals = ['I', 'V', 'X', 'L', 'C', 'D', 'M']
const createRomanNumeralRange = (I, V, X) => [
'',
I,
`${I}${I}`,
`${I}${I}${I}`,
`${I}${V}`,
V,
`${V}${I}`,
`${V}${I}${I}`,
`${V}${I}${I}${I}`,
`${I}${X}`,
]
return Array.from(String(int))
.reverse()
.reduce((prevRomanNumerals, numeral, index) => {
const nextRomanNumeral = createRomanNumeralRange(
...romanNumerals.slice(index * 2, index * 2 + 3),
)[numeral]
return `${nextRomanNumeral}${prevRomanNumerals}`
}, '')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment