Last active
March 20, 2024 23:12
-
-
Save ecancino/e5140e4a62a4600db10df46f3092dcc1 to your computer and use it in GitHub Desktop.
Convert roman to arabic numerals
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 ROMAN_ARABIC_CONVERSION = { | |
| I: 1, | |
| V: 5, | |
| X: 10, | |
| L: 50, | |
| C: 100, | |
| D: 500, | |
| M: 1_000, | |
| V̅: 5_000, | |
| X̅: 10_000, | |
| L̅: 50_000, | |
| C̅: 100_000, | |
| D̅: 500_000, | |
| M̅: 1_000_000, | |
| } as const; | |
| type RomanSymbol = keyof typeof ROMAN_ARABIC_CONVERSION; | |
| const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" }); | |
| function split(str: string): string[] { | |
| return Array.from(segmenter.segment(str), ({ segment }) => segment); | |
| } | |
| function fromRomanNumerals(roman: string): number { | |
| const symbolList = split(roman); | |
| return symbolList.reduce<number>((total, sym, index) => { | |
| const currentValue = ROMAN_ARABIC_CONVERSION[sym as RomanSymbol]; | |
| const nextValue = | |
| ROMAN_ARABIC_CONVERSION[symbolList[index + 1] as RomanSymbol] ?? 0; | |
| const value = nextValue > currentValue ? -currentValue : currentValue; | |
| return total + value; | |
| }, 0); | |
| } | |
| console.log(fromRomanNumerals("MCMLXXVII")); | |
| console.log(fromRomanNumerals("IV")); | |
| console.log(fromRomanNumerals("IX")); | |
| console.log(fromRomanNumerals("XL")); | |
| console.log(fromRomanNumerals("XC")); | |
| console.log(fromRomanNumerals("CD")); | |
| console.log(fromRomanNumerals("CM")); | |
| console.log(fromRomanNumerals("V̅")); | |
| console.log(fromRomanNumerals("X̅")); | |
| console.log(fromRomanNumerals("L̅")); | |
| console.log(fromRomanNumerals("C̅")); | |
| console.log(fromRomanNumerals("D̅")); | |
| console.log(fromRomanNumerals("M̅")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment