Skip to content

Instantly share code, notes, and snippets.

@ngsctt
Created January 22, 2020 16:55
Show Gist options
  • Save ngsctt/ea419c8ae4b35c4bd8e389a39b9709bc to your computer and use it in GitHub Desktop.
Save ngsctt/ea419c8ae4b35c4bd8e389a39b9709bc to your computer and use it in GitHub Desktop.
JavaScript to convert numbers between 1 and 1,999,999 to roman numerals
function romanise (number, upper=true) {
if (number > 1999999) {
console.warn('WARN: attempted to convert number over 1,999,999 to roman numeral');
return number;
}
const letters = upper ? [
['X', 'V', 'I'],
['C', 'L', 'X'],
['M', 'D', 'C'],
['X̅', 'V̅', 'M'],
['C̅', 'L̅', 'X̅'],
['M̅', 'D̅', 'C̅']
] : [
['x', 'v', 'i'],
['c', 'l', 'x'],
['m', 'd', 'c'],
['x̅', 'v̅', 'm'],
['c̅', 'l̅', 'x̅'],
['m̅', 'd̅', 'c̅']
];
function toText (n, X, V, I) {
let out = '';
let r = n % 10;
if (n > 0 && r === 0) out = X;
else if (r <= 3) for (i=0; i<r; i++) out += I;
else if (r < 5) out += I + V;
else if (r <= 8) {
out = V;
for (i=0; i<(r-5); i++) out += I;
} else {
for (i=0; i<(10-r); i++) out += I;
out += X;
}
return out;
}
function recurse (q, depth) {
let out = '';
let remainder = q % 10;
let quotient = (q - remainder) / 10;
out += toText(remainder, ...letters[depth]);
if (quotient > 0) out = recurse(quotient, depth + 1) + out;
return out;
}
return recurse(number,0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment