Skip to content

Instantly share code, notes, and snippets.

@J2D2Development
Created July 22, 2017 03:45
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 J2D2Development/2c1e8d7aed42b2f036b391d081faa76a to your computer and use it in GitHub Desktop.
Save J2D2Development/2c1e8d7aed42b2f036b391d081faa76a to your computer and use it in GitHub Desktop.
//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