refactor: improve conversion to roman numerals
This commit is contained in:
parent
658c538b6a
commit
f38adb5e02
1 changed files with 11 additions and 17 deletions
|
@ -18,29 +18,23 @@ const helpers = {
|
||||||
};
|
};
|
||||||
|
|
||||||
function toRomanNumerals(number: number): string {
|
function toRomanNumerals(number: number): string {
|
||||||
return toRomanNumeralsRecurse(number, numerals) ?? "";
|
return [...generateRomanNumerals(number, 0)].join("");
|
||||||
}
|
}
|
||||||
|
|
||||||
function toRomanNumeralsRecurse(number: number, numerals: number[]): string | undefined {
|
function* generateRomanNumerals(number: number, numeralIndex: number): Generator<string> {
|
||||||
if (number === 0) {
|
if (number === 0) return;
|
||||||
return undefined;
|
const currentNumeral = numerals[numeralIndex];
|
||||||
}
|
if (currentNumeral === undefined) return;
|
||||||
const currentNumeral = numerals[0];
|
|
||||||
if (currentNumeral === undefined) {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
const quotient = number / currentNumeral;
|
const quotient = number / currentNumeral;
|
||||||
const remainder = number % currentNumeral;
|
const remainder = number % currentNumeral;
|
||||||
const numberAsNumerals = numeralLookup[currentNumeral]?.repeat(quotient);
|
const numberAsNumerals = numeralLookup[currentNumeral].repeat(quotient);
|
||||||
if (numberAsNumerals === undefined) {
|
|
||||||
return undefined;
|
yield numberAsNumerals;
|
||||||
}
|
yield* generateRomanNumerals(remainder, numeralIndex + 1);
|
||||||
const [, ...remainingNumerals] = numerals;
|
|
||||||
return numberAsNumerals + (toRomanNumeralsRecurse(remainder, remainingNumerals) ?? "");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const numeralLookup: Record<number, string> = {
|
const numeralLookup = {
|
||||||
1: "I",
|
1: "I",
|
||||||
2: "II",
|
2: "II",
|
||||||
3: "III",
|
3: "III",
|
||||||
|
@ -73,4 +67,4 @@ const numeralLookup: Record<number, string> = {
|
||||||
|
|
||||||
const numerals = [
|
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,
|
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