Skip to content

Commit

Permalink
new %m specifier for string formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
vytdev committed Feb 23, 2024
1 parent c124a15 commit d9bb65f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
17 changes: 14 additions & 3 deletions src/catalyst/core/locale.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/**
* localization helpers
*/
import { toRomanNumeral } from "./utils.js";

/**
* a string wrapper for translatable strings
Expand Down Expand Up @@ -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, // #
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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, ' ');
Expand Down
2 changes: 1 addition & 1 deletion src/catalyst/core/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit d9bb65f

Please sign in to comment.