Skip to content

Instantly share code, notes, and snippets.

@johncmunson
Created January 29, 2017 03:19
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 johncmunson/b68559709374b1e4ac9def1cb7d42c61 to your computer and use it in GitHub Desktop.
Save johncmunson/b68559709374b1e4ac9def1cb7d42c61 to your computer and use it in GitHub Desktop.
Accepts a roman numeral and returns the corresponding integer.
var deromanize = function(str) {
var str = str.toUpperCase(),
validator = /^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/,
token = /[MDLV]|C[MD]?|X[CL]?|I[XV]?/g,
key = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1
},
num = 0, m;
if (!(str && validator.test(str))) {
return false;
}
while (m = token.exec(str)) {
num += key[m[0]];
}
return num;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment