From d9bb65f75cff612734849cb3182de6d30bab27f9 Mon Sep 17 00:00:00 2001 From: vytdev <123163428+vytdev@users.noreply.github.com> Date: Fri, 23 Feb 2024 20:09:40 +0800 Subject: [PATCH] new %m specifier for string formatting --- src/catalyst/core/locale.ts | 17 ++++++++++++++--- src/catalyst/core/utils.ts | 2 +- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/catalyst/core/locale.ts b/src/catalyst/core/locale.ts index d8cbe70..e94207a 100644 --- a/src/catalyst/core/locale.ts +++ b/src/catalyst/core/locale.ts @@ -1,6 +1,7 @@ /** * localization helpers */ +import { toRomanNumeral } from "./utils.js"; /** * a string wrapper for translatable strings @@ -42,7 +43,7 @@ export interface formatPlaceHolder { /** length modifier */ lengthModifier?: 'hh'|'h'|'ll'|'l'|'j'|'z'|'t'|'L', /** conversion specifier */ - specifier: '%'|'?'|'c'|'s'|'d'|'i'|'o'|'b'|'x'|'X'|'u'|'f'|'F'|'e'|'E'|'a'|'A'|'g'|'G', + specifier: '%'|'?'|'c'|'s'|'d'|'i'|'o'|'b'|'x'|'X'|'u'|'f'|'F'|'e'|'E'|'a'|'A'|'g'|'G'|'m', // flags alternate: boolean, // # @@ -202,7 +203,7 @@ export function parseFormat(format: string): formatTokens { if (!c) incompleteFormat(); // check if c is a specifier - if (!'%?csdiobxXufFeEaAgG'.includes(c)) + if (!'%?csdiobxXufFeEaAgGm'.includes(c)) throw new TypeError('unknown conversion specifier: ' + c); // the specifier @@ -290,7 +291,7 @@ export function applyFormat(format: formatTokens, ...args: any[]): string { let arg = ''; // validate conversion specifier - if (!'%?csdiobxXufFeEaAgG'.includes(spec)) + if (!'%?csdiobxXufFeEaAgGm'.includes(spec)) throw new TypeError('unknown conversion specifier: ' + spec); // incompatible types error @@ -547,6 +548,16 @@ export function applyFormat(format: formatTokens, ...args: any[]): string { if (spec == 'A') arg = arg.toUpperCase(); } + // 'm' specifier (custom) + // write roman numerals + if (spec == 'm') { + if (typeof source != 'number') invalidArg(); + // generate roman numerals + arg = toRomanNumeral(source); + // use lowercase + if (tok.alternate) arg = arg.toLowerCase(); + } + // padding if (tok.leftAlign) arg = arg.padEnd(minFieldWidth, ' '); else arg = arg.padStart(minFieldWidth, ' '); diff --git a/src/catalyst/core/utils.ts b/src/catalyst/core/utils.ts index ccd92a0..9890451 100644 --- a/src/catalyst/core/utils.ts +++ b/src/catalyst/core/utils.ts @@ -80,7 +80,7 @@ export function formatNumber(n: number): string { * @param n the number * @returns result string */ -export function toRomanNumeral(num: number) { +export function toRomanNumeral(num: number): string { // NOTES: // - no negative // - no decimals