Skip to content

Instantly share code, notes, and snippets.

@mcshaman
Last active September 23, 2015 09:47
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 mcshaman/028e03c187554ebc46d5 to your computer and use it in GitHub Desktop.
Save mcshaman/028e03c187554ebc46d5 to your computer and use it in GitHub Desktop.
Javascript function that converts roman numeral style ordered list strings to number
function romanToNumber( str ) {
var string = str.toUpperCase(),
letters = string.split( '' ),
length = letters.length,
i,
mapping = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 },
values = [],
valueA,
valueB,
number = 0;
// Validate string
if( ! string.match( /^M{0,3}(CM)?(CD|D?C{0,3})(XC)?(XL|L?X{0,3})(IX)?(IV|V?I{0,3})$/ ) ) {
throw new Error( 'Not a valid roman numeral string' );
}
// Convert all roman numerals to numbers
for( i = 0; i < length; i++ ) {
values[ i ] = mapping[ letters[ i ] ];
}
// If only one value return it
if( length == 1 ) {
return values[ 0 ];
}
// Calculate number from values
for( i = 0; i <= length; i++ ) {
valueA = values[ i ];
if( typeof valueB !== 'undefined' ) { // Not first
if( valueA > valueB ) { // Left number smaller than right so negate
number -= valueB;
} else {
number += valueB; // Left number is greater than right or right is undefind so add
}
}
valueB = valueA;
}
return number;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment