Skip to content

Instantly share code, notes, and snippets.

@codfish
Created April 13, 2020 14:45
Show Gist options
  • Save codfish/0497f5d1d9e9f28dcc836a1b6bfb45f7 to your computer and use it in GitHub Desktop.
Save codfish/0497f5d1d9e9f28dcc836a1b6bfb45f7 to your computer and use it in GitHub Desktop.
Convert decimal number to Roman numeral
const NUMERALS = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
IV: 4,
IX: 9,
XL: 40,
XC: 90,
CD: 100,
CM: 900,
};
const romanToDecimal = (numerals) => {
// validate here
let value = 0;
// loop through the roman numeral string
for (let i = 0; i < numerals.length; i += 1) {
// create a combo numeral with this index and it's
// next sibling
let combo = `${numerals[i]}${numerals[i + 1]}`;
// check to see if the combo has a value
if (NUMERALS[combo]) {
// if it does, add to the total value, and increment the
// loop by an extra 1, so that the next sibling doesn't
// get counted again
value += NUMERALS[combo];
i += 1;
continue;
}
// combo didn't have a value, so let's just try the single numeral
if (NUMERALS[numerals[i]]) {
value += NUMERALS[numerals[i]];
continue;
} else {
// hmm, combo and single numeral did not have an associated
// decimal value, so let's set `value` to false and break out
// of the loop, cause this looks to be an invalid roman numeral
value = false;
break;
}
}
return value;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment