Skip to content

Instantly share code, notes, and snippets.

@taverasmisael
Last active June 30, 2023 19:52
Show Gist options
  • Save taverasmisael/fef2b6e8253dd91eac6ba0052c8cdf93 to your computer and use it in GitHub Desktop.
Save taverasmisael/fef2b6e8253dd91eac6ba0052c8cdf93 to your computer and use it in GitHub Desktop.
A simple gist to convert roman numbers to decimal using reduceRight
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