refactor: improve conversion to roman numerals
This commit is contained in:
parent
658c538b6a
commit
f38adb5e02
|
@ -18,29 +18,23 @@ const helpers = {
|
|||
};
|
||||
|
||||
function toRomanNumerals(number: number): string {
|
||||
return toRomanNumeralsRecurse(number, numerals) ?? "";
|
||||
return [...generateRomanNumerals(number, 0)].join("");
|
||||
}
|
||||
|
||||
function toRomanNumeralsRecurse(number: number, numerals: number[]): string | undefined {
|
||||
if (number === 0) {
|
||||
return undefined;
|
||||
}
|
||||
const currentNumeral = numerals[0];
|
||||
if (currentNumeral === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
function* generateRomanNumerals(number: number, numeralIndex: number): Generator<string> {
|
||||
if (number === 0) return;
|
||||
const currentNumeral = numerals[numeralIndex];
|
||||
if (currentNumeral === undefined) return;
|
||||
|
||||
const quotient = number / currentNumeral;
|
||||
const remainder = number % currentNumeral;
|
||||
const numberAsNumerals = numeralLookup[currentNumeral]?.repeat(quotient);
|
||||
if (numberAsNumerals === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
const [, ...remainingNumerals] = numerals;
|
||||
return numberAsNumerals + (toRomanNumeralsRecurse(remainder, remainingNumerals) ?? "");
|
||||
const numberAsNumerals = numeralLookup[currentNumeral].repeat(quotient);
|
||||
|
||||
yield numberAsNumerals;
|
||||
yield* generateRomanNumerals(remainder, numeralIndex + 1);
|
||||
}
|
||||
|
||||
const numeralLookup: Record<number, string> = {
|
||||
const numeralLookup = {
|
||||
1: "I",
|
||||
2: "II",
|
||||
3: "III",
|
||||
|
@ -73,4 +67,4 @@ const numeralLookup: Record<number, string> = {
|
|||
|
||||
const numerals = [
|
||||
1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
|
||||
];
|
||||
] as const;
|
||||
|
|
Loading…
Reference in a new issue