const romanNumerals: Record<string, number> = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
}
const convertToNumber = (romanNumeral: string): number => {
const romanDigits = romanNumeral.split('')
return romanDigits.reduce(
(acc: number, curr: string, index: number) =>
romanNumerals[curr] < romanNumerals[romanDigits[index + 1]]
? acc - romanNumerals[curr]
: acc + romanNumerals[curr],
0
)
}
console.log(convertToNumber('XXXIX'))
// returns 39
console.log(convertToNumber('XL'))
// returns 40
console.log(convertToNumber('MMXXI'))
// returns 2021
console.log(convertToNumber('CLX'))
// returns 160
console.log(convertToNumber('DCCLXXXIX'))
// returns 789
console.log(convertToNumber('MCMXVIII'))
// returns 1918
console.log(convertToNumber('MMMCMXCIX'))
// returns 3999