Created
February 6, 2019 02:11
-
-
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)
This file contains hidden or 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 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