Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
//smaller conversions map object, large ugly helper function, too specific conditional logic in main
const conversions = {
thousandsLetter: 'M', fiveHundredLetter: 'D', hundredsLetter: 'C', fiftyLetter: 'L',
tensLetter: 'X', fiveLetter: 'V', onesLetter: 'I'
};
function convert(n, letter, midLetter, nextLetter) {
let origNum = Number(n);
if(origNum === 0) {
return '';
} else if(origNum > 0 && origNum < 4) {
return letter.repeat(origNum);
} else if(origNum === 4) {
return letter + midLetter;
} else if(origNum === 5) {
return midLetter;
} else if(origNum > 5 && origNum < 9) {
return midLetter + letter.repeat(origNum - 5);
} else {
return letter + nextLetter;
}
}
function convertToRoman(num) {
const numArray = String(num).split('');
const len = numArray.length;
const ones = convert(numArray[len - 1], conversions.onesLetter, conversions.fiveLetter, conversions.tensLetter);
let thousands, hundreds, tens;
let ansArr = [ones];
if(numArray[len - 2]) {
tens = convert(Number(numArray[len - 2]), conversions.tensLetter, conversions.fiftyLetter, conversions.hundredsLetter);
ansArr.unshift(tens);
}
if(numArray[len - 3]) {
hundreds = convert(Number(numArray[len - 3]), conversions.hundredsLetter, conversions.fiveHundredLetter, conversions.thousandsLetter);
ansArr.unshift(hundreds);
}
if(numArray[len - 4]) {
thousands = conversions.thousandsLetter.repeat(Number(numArray[0]));
ansArr.unshift(thousands);
}
return ansArr.join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment