Skip to content

Instantly share code, notes, and snippets.

@hassan-maavan
Created September 19, 2020 06:18
Show Gist options
  • Save hassan-maavan/318b3c3d48c1607345c3ee45d93db3a4 to your computer and use it in GitHub Desktop.
Save hassan-maavan/318b3c3d48c1607345c3ee45d93db3a4 to your computer and use it in GitHub Desktop.
Create a RomanNumerals class that can convert a roman numeral to and from an integer value. It should follow the API demonstrated in the examples below. Multiple roman numeral values will be tested for each helper method. Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digi…
var RomanNumerals = {
toRoman : function (number) {
var ret = '';
while(number > 0) {
if(number/1000 >= 1) {
ret += 'M';
number -=1000;
} else if(number/900 >= 1) {
ret += 'CM';
number -=900;
} else if(number/500 >= 1) {
ret += 'D';
number -=500;
} else if(number/400 >= 1) {
ret += 'CD';
number -=400;
} else if(number/100 >= 1) {
ret += 'C';
number -=100;
} else if(number/90 >= 1) {
ret += 'XC';
number -=90;
} else if(number/50 >= 1) {
ret += 'L';
number -=50;
} else if(number/40 >= 1) {
ret += 'XL';
number -=40;
} else if(number/10 >= 1) {
ret += 'X';
number -=10;
} else if(number/9 >= 1) {
ret += 'IX';
number -=9;
} else if(number/5 >= 1) {
ret += 'V';
number -=5;
} else if(number/4 >= 1) {
ret += 'IV';
number -=4;
} else if(number/1 >= 1) {
ret += 'I';
number -=1;
}
}
return ret;
}
,fromRoman : function(str) {
var ret = 0;
while(str.length > 0) {
switch(str.charAt(0)) {
case 'M':
str = str.slice(1);
ret+=1000;
break;
case 'D':
str = str.slice(1);
ret+=500;
break;
case 'L':
str = str.slice(1);
ret+=50;
break;
case 'C':
if(str.charAt(1) === 'M') {
str = str.slice(2);
ret+=900;
} else if(str.charAt(1) === 'D') {
str = str.slice(2);
ret+=400;
} else {
str = str.slice(1);
ret+=100;
} break;
case 'X':
if(str.charAt(1) === 'C') {
str = str.slice(2);
ret+=90;
} else if(str.charAt(1) === 'L') {
str = str.slice(2);
ret+=40;
} else {
str = str.slice(1);
ret+=10;
} break;
case 'V':
str = str.slice(1);
ret+=5;
break;
case 'I':
if(str.charAt(1) === 'X') {
str = str.slice(2);
ret+=9;
} else if(str.charAt(1) === 'V') {
str = str.slice(2);
ret+=4;
} else {
str = str.slice(1);
ret+=1;
} break;
}
}
return ret;
}
}
RomanNumerals.toRoman('M');
@nccharles
Copy link

nccharles commented Dec 9, 2021

const dec = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
const rom = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];

class RomanNumerals {
static fromRoman(str) {
return str.match(/CM|CD|XC|XL|IX|IV|\w/g).reduce((pre, val) => pre + dec[rom.indexOf(val)], 0);
}

static toRoman(num) {
return dec.reduce((pre, val, idx) => pre + rom[idx].repeat(num / val ^ 0, num -= val * (num / val ^ 0)), ``);
}
}

console.log(RomanNumerals.toRoman(1000))

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