Last active
May 25, 2022 21:22
-
-
Save luan0ap/c0e3962a2d6014503007694ce4c8346d to your computer and use it in GitHub Desktop.
Convert roman numerals to numerals using recursive solution
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
/** | |
* | |
* @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