Skip to content

Instantly share code, notes, and snippets.

@ded
Created November 25, 2010 20:22
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 ded/715864 to your computer and use it in GitHub Desktop.
Save ded/715864 to your computer and use it in GitHub Desktop.
You never know when you might need to convert digits to roman numerals
var table = ['i', 'v', 'x', 'l', 'c', 'd', 'm'];
var map = {
4: "01",
5: "1",
6: "10",
7: "100",
8: "1000",
9: "02"
};
function convert(num) {
if (num > 9999) {
// invalid roman numeral
// since roman numerals are based on dates, Romans clearly weren't visionaries
return 'eat a bag of dicks';
}
n = num.toString();
var value = [];
for (var i = n.length - 1, j = 0; i >= 0; i--, j = j + 2) {
var c = Array(parseInt(n[i], 10) + 1).join(table[j]);
value.unshift(c);
}
value = value.join('');
for (var i=0; i < table.length; i = i + 2) {
var letter = table[i];
var reg = new RegExp(letter + "{4,9}");
var found = value.match(reg);
if (found && i !== table.length - 1) {
var key = map[found[0].length];
var newKey = [table[i], table[i + 1], table[i + 2]];
var replacer = key.split('').map(function(el) {
return newKey[parseInt(el, 10)];
}).join('');
value = value.replace(reg, replacer);
}
}
return value.toUpperCase();
}
// all cases should be true
console.log(convert(1) == 'I');
console.log(convert(3) == 'III');
console.log(convert(4) == 'IV');
console.log(convert(5) == 'V');
console.log(convert(9) == 'IX');
console.log(convert(10) == 'X');
console.log(convert(19) == 'XIX');
console.log(convert(50) == 'L');
console.log(convert(100) == 'C');
console.log(convert(1000) == 'M');
console.log(convert(1944) == 'MCMXLIV');
console.log(convert(1999) == 'MCMXCIX');
console.log(convert(888) == 'DCCCLXXXVIII');
console.log(convert(9999) == 'MMMMMMMMMCMXCIX');
console.log(convert(51) == 'LI');
console.log(convert(56) == 'LVI');
console.log(convert(118) == 'CXVIII');
console.log(convert(119) == 'CXIX');
@fabianperez
Copy link

Line 16 is pure gold.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment