Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
//small conversion array, still somewhat ugly helper logic, simple loop in main
const conversions = [
{nextLetter: 'X', midLetter: 'V', letter: 'I'},
{nextLetter: 'C', midLetter: 'L', letter: 'X'},
{nextLetter: 'M', midLetter: 'D', letter: 'C'}
];
function convert(n, legend) {
let origNum = Number(n);
if(origNum === 0) {
return '';
} else if(origNum > 0 && origNum < 4) {
return legend.letter.repeat(origNum);
} else if(origNum === 4) {
return legend.letter + legend.midLetter;
} else if(origNum === 5) {
return legend.midLetter;
} else if(origNum > 5 && origNum < 9) {
return legend.midLetter + legend.letter.repeat(origNum - 5);
} else {
return legend.letter + legend.nextLetter;
}
}
function convertToRoman(num) {
const numArray = String(num).split('');
const len = numArray.length;
let ansArr = [];
for(let i = 0; i < len; i += 1) {
let toPush;
if(len === 4 && i === 0) {
toPush = 'M'.repeat(numArray[i]);
} else {
let convMatrix = conversions[len - 1 - i];
toPush = convert(numArray[i], convMatrix);
}
ansArr.push(toPush);
}
return ansArr.join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment