Created
March 24, 2020 19:48
-
-
Save fed135/5a8ce312d68c592ee1c2ea8d44c3b497 to your computer and use it in GitHub Desktop.
Roman numeral to integer parser
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
function romanToNum(str) { | |
const symbols = 'IVXLCDM'; | |
let acc = ''; | |
// Reverse iterate through the provided characters | |
for (let i = str.length - 1; i >= 0; i--) { | |
// Get the associated roman character symbol's order in the list | |
let index = symbols.indexOf(str[i]); | |
// Calculate the value for the symbol 1 || 5 ^ 10 based on the previous index value | |
let value = (index % 2 === 0 ? 1 : 5) * (10**(index>>1)); | |
// Append the value to the math equation that we'll eval at the end | |
acc += value; | |
// Add either a + or a - based on the index value of the following character | |
if (i !== 0) { | |
if (i > 0 && symbols.indexOf(str[i-1]) < index) acc += '-'; | |
else acc += '+'; | |
} | |
} | |
return Number(eval(acc)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment