Skip to content

Instantly share code, notes, and snippets.

@RickJP
Created April 10, 2019 12:40
Show Gist options
  • Save RickJP/3a024545b68f6585447440a135fc97a9 to your computer and use it in GitHub Desktop.
Save RickJP/3a024545b68f6585447440a135fc97a9 to your computer and use it in GitHub Desktop.
JS - Roman Numeral <-> Number Converter
function romanize(num) {
var lookup = {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},
roman = '',
i;
for ( i in lookup ) {
while ( num >= lookup[i] ) {
roman += i;
num -= lookup[i];
}
}
return roman;
}
function deromanize( roman ) {
var roman = roman.toUpperCase(),
lookup = {I:1,V:5,X:10,L:50,C:100,D:500,M:1000},
arabic = 0,
i = roman.length;
while (i--) {
if ( lookup[roman[i]] < lookup[roman[i+1]] )
arabic -= lookup[roman[i]];
else
arabic += lookup[roman[i]];
}
return arabic;
====================================================================================================
var romanMatrix = [
[1000, 'M'],
[900, 'CM'],
[500, 'D'],
[400, 'CD'],
[100, 'C'],
[90, 'XC'],
[50, 'L'],
[40, 'XL'],
[10, 'X'],
[9, 'IX'],
[5, 'V'],
[4, 'IV'],
[1, 'I']
];
function convertToRoman(num) {
if (num === 0) {
return '';
}
for (var i = 0; i < romanMatrix.length; i++) {
if (num >= romanMatrix[i][0]) {
return romanMatrix[i][1] + convertToRoman(num - romanMatrix[i][0]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment