Skip to content

Instantly share code, notes, and snippets.

@christophemarois
Last active January 26, 2018 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christophemarois/26fcd93e12725fabf58c to your computer and use it in GitHub Desktop.
Save christophemarois/26fcd93e12725fabf58c to your computer and use it in GitHub Desktop.
Convert a roman numeral to a number
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