Last active
January 26, 2018 19:44
-
-
Save christophemarois/26fcd93e12725fabf58c to your computer and use it in GitHub Desktop.
Convert a roman numeral to a number
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
const dict = [ | |
['CM', 900], ['M', 1000], ['CD', 400], ['D', 500], | |
['XC', 90], ['C', 100], ['XL', 40], ['L', 50], | |
['IX', 9], ['X', 10], ['IV', 4], ['V', 5], | |
['I', 1], | |
] | |
function romanToInt (original) { | |
let temp = original | |
let int = 0 | |
while (temp.length > 0) { | |
let found = false | |
for (const [glyph, quantity] of dict) { | |
if (temp.startsWith(glyph)) { | |
int += quantity | |
temp = temp.slice(glyph.length) | |
found = true | |
break | |
} | |
} | |
if (!found) { | |
throw new Error(`Error parsing roman numeral "${original}" at "${temp}"`) | |
} | |
} | |
return int | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment