Created
July 30, 2023 04:06
-
-
Save BRonen/15c87ae96d38ae700927d20e3f20dc8d to your computer and use it in GitHub Desktop.
Script to parse roman numerals to equivalent integer
This file contains 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
/** | |
* Decodes a Roman numeral to a number. | |
* | |
* @param {string} roman - The Roman numeral to decode. | |
* @returns {number} The decoded Roman numeral. | |
*/ | |
const numerals: Record<string, number> = { | |
'I': 1, | |
'V': 5, | |
'X': 10, | |
'L': 50, | |
'C': 100, | |
'D': 500, | |
'M': 1000, | |
} | |
const evaluateNumbersList = (list: number[]): number => { | |
const [first, second] = list.slice(0, 2) | |
if(!first) | |
return 0; | |
if(!second) | |
return first; | |
if(first < second) | |
return (second - first) + evaluateNumbersList(list.slice(2)); | |
return first + evaluateNumbersList([second, ...list.slice(2)]); | |
}; | |
const decode = (roman: string): number => { | |
const parsedValues = roman.split('').map(char => numerals[char]); | |
return evaluateNumbersList(parsedValues); | |
}; | |
export { decode }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment