Skip to content

Instantly share code, notes, and snippets.

@luan0ap
Last active May 25, 2022 21:22
Show Gist options
  • Save luan0ap/c0e3962a2d6014503007694ce4c8346d to your computer and use it in GitHub Desktop.
Save luan0ap/c0e3962a2d6014503007694ce4c8346d to your computer and use it in GitHub Desktop.
Convert roman numerals to numerals using recursive solution
/**
*
* @param {Strig} roman roman numeral like
* @throws {RangeError} if roman is not a valid roman numeral
* @returns Number
*/
function romanNumeralToNumeral (roman = '') {
if (!roman.match(/^[IVXLCDM]+$/)) {
throw new RangeError('Invalid roman numeral')
}
const romanToNumeralPairs = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
}
const converter = (curIndex = 0, result = 0) => {
if (roman.length > curIndex) {
const current = roman[curIndex]
const next = roman[curIndex + 1]
const nextResult = romanToNumeralPairs[current] < romanToNumeralPairs[next] ? result - romanToNumeralPairs[current] : result + romanToNumeralPairs[current]
return converter(curIndex + 1, nextResult)
}
return result
}
return converter()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment