Skip to content

Instantly share code, notes, and snippets.

@ribaptista
Created February 19, 2020 23:19
Show Gist options
  • Save ribaptista/77c22c723f37ec6efa735b40a29f90ca to your computer and use it in GitHub Desktop.
Save ribaptista/77c22c723f37ec6efa735b40a29f90ca to your computer and use it in GitHub Desktop.
const toPairs = roman => roman.map((v, i, array) => array.slice(i, i + 2))
const toValues = pairs => pairs.map(([p, n = 0]) => ([romanChars[p], romanChars[n]]))
const toParts = pairs => pairs.map(([p, n = 0]) => p >= n ? p : -p)
const toSum = parts => parts.reduce((part, sum) => sum + part, 0)
const romanChars = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
0: 0
}
const toInt = roman => toSum(toParts(toValues(toPairs(roman.split('')))))
console.log(toInt('XXVI'));
console.log(toInt('CI'));
console.log(toInt('IX'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment