Skip to content

Instantly share code, notes, and snippets.

@i-anshuman
Last active November 14, 2019 16:37
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 i-anshuman/896c00ee0305e10f61cb7c3faa13c24f to your computer and use it in GitHub Desktop.
Save i-anshuman/896c00ee0305e10f61cb7c3faa13c24f to your computer and use it in GitHub Desktop.
FreeCodeCamp: Roman Numeral Converter
'use strict';
const getRange = (num, list) => {
return [
list.reduce((previous, current) => {
return (previous < num && num < current) ? previous : current;
}),
list.reduce((previous, current) => {
return (previous < num && num < current) ? current : previous;
})
]
}
const isInRange = (num, range) => {
return range.reduce((previous, current) => previous < num && num < current);
}
const convertToRoman = (num) => {
let romanNumber = '';
const romanDigits = {
1: 'I',
5: 'V',
10: 'X',
50: 'L',
100: 'C',
500: 'D',
1000: 'M'
};
const romanList = Object.keys(romanDigits).map(n => Number(n));
if (romanList.includes(num)) {
romanNumber = romanDigits[num];
}
else {
let [floor, ceil] = getRange(num, romanList);
let quotient = 0;
let remainder = 0;
if (isInRange(num, [floor, ceil-floor])) {
quotient = parseInt(num / floor);
remainder = num % floor;
romanNumber = romanDigits[floor].repeat(quotient);
}
else if (num > 1000 && num < 4000) {
quotient = parseInt(num / 1000);
remainder = num % 1000;
romanNumber = romanDigits[floor].repeat(quotient);
}
else {
if (/^5/.test(floor) && (ceil - romanList[romanList.indexOf(floor) - 1]) <= num) {
quotient = parseInt(num / romanList[romanList.indexOf(floor) - 1])
remainder = num % romanList[romanList.indexOf(floor) - 1];
romanNumber = romanDigits[romanList[romanList.indexOf(floor) - 1]] + romanDigits[ceil];
}
else {
remainder = num % (ceil-floor);
romanNumber += romanDigits[floor] + ((/^5/.test(floor)) ? '' : romanDigits[ceil]);
}
}
if (remainder > 0) {
romanNumber += convertToRoman(remainder);
}
}
return romanNumber;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment