Created
July 22, 2017 03:45
-
-
Save J2D2Development/2c1e8d7aed42b2f036b391d081faa76a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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