Skip to content

Instantly share code, notes, and snippets.

@fed135
Created March 24, 2020 19:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fed135/5a8ce312d68c592ee1c2ea8d44c3b497 to your computer and use it in GitHub Desktop.
Save fed135/5a8ce312d68c592ee1c2ea8d44c3b497 to your computer and use it in GitHub Desktop.
Roman numeral to integer parser
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