Last active
June 30, 2023 19:52
-
-
Save taverasmisael/fef2b6e8253dd91eac6ba0052c8cdf93 to your computer and use it in GitHub Desktop.
A simple gist to convert roman numbers to decimal using reduceRight
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 VALUES = { | |
I: 1, | |
V: 5, | |
X: 10, | |
L: 50, | |
C: 100, | |
D: 500, | |
M: 1000, | |
} | |
const INIT = { value: 0, prev: 0 } | |
const romanToDecimal = (roman: string) => | |
roman | |
.split('') | |
.map((s) => VALUES[s] || 0) // SUPER EDGE CASE | |
.reduceRight( | |
(acc, value) => ({ value: value >= acc.prev ? value + acc.value : acc.value - value, prev: value }), | |
INIT | |
).value | |
romanToDecimal('XXI') // 21 | |
romanToDecimal('VXXI') // 16 (but wrong) | |
romanToDecimal('IV') // 4 | |
romanToDecimal('XVI') // 16 (but right) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment