wealth/packages/tools/src/format/format.ts

158 lines
5.1 KiB
TypeScript
Raw Normal View History

2026-10-02 15:42:11 +00:00
import {
ARABIC_DIGITS,
DAY_MS,
DECIMAL_SEPARATOR,
HOUR_MS,
LOCALE,
LTR_ISOLATE_END,
LTR_ISOLATE_START,
MINUS_SIGN,
MINUTE_MS,
PERCENT_SIGN,
PERSIAN_DIGITS,
THOUSANDS_SEPARATOR,
TIME_ZONE,
} from './constants';
import type { DateFormatOptions, DateInput, ShebaFormatOptions } from './types';
// Formatters are built once per fixed locale and time zone (flyweight); they never hold per-request data.
const dateFormatter = new Intl.DateTimeFormat(LOCALE, {
timeZone: TIME_ZONE,
day: 'numeric',
month: 'long',
year: 'numeric',
});
const dateTimeFormatter = new Intl.DateTimeFormat(LOCALE, {
timeZone: TIME_ZONE,
day: 'numeric',
month: 'long',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
hourCycle: 'h23',
});
const relativeFormatter = new Intl.RelativeTimeFormat(LOCALE, {
numeric: 'auto',
});
const numberFormatters = new Map<number, Intl.NumberFormat>();
function numberFormatter(decimals: number): Intl.NumberFormat {
let formatter = numberFormatters.get(decimals);
if (!formatter) {
formatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: decimals,
maximumFractionDigits: decimals,
});
numberFormatters.set(decimals, formatter);
}
return formatter;
}
function persianSeparators(value: string): string {
return value.replace(/[,.]/g, (char) =>
char === ',' ? THOUSANDS_SEPARATOR : DECIMAL_SEPARATOR,
);
}
function toDate(value: DateInput): Date {
return value instanceof Date ? value : new Date(value);
}
/** Wraps text in an LTR isolate so signs, percents and codes keep their order inside RTL copy. */
export function iso(value: string): string {
return `${LTR_ISOLATE_START}${value}${LTR_ISOLATE_END}`;
}
/** Converts Persian and Arabic digits to Latin ones; use it on every input before validation. */
export function latinDigits(value: string): string {
return value.replace(/[۰-۹٠-٩]/g, (digit) => {
const persian = PERSIAN_DIGITS.indexOf(digit);
return String(persian === -1 ? ARABIC_DIGITS.indexOf(digit) : persian);
});
}
/** `1234567.8` → `1٬234٬567٫8`. The font draws the digits in Persian. */
export function number(value: number, decimals = 0): string {
return persianSeparators(
numberFormatter(decimals).format(Math.abs(value)),
).replace(/^/, value < 0 ? MINUS_SIGN : '');
}
/** A price keeps the decimals it has: `1.092` → `1٫092`. */
export function price(value: number): string {
const decimals = Math.min(value.toString().split('.')[1]?.length ?? 0, 8);
return number(value, decimals);
}
/** Always shows `+` or `−`, inside an LTR isolate: `−120٬000`. */
export function signed(value: number, decimals = 0): string {
const sign = value > 0 ? '+' : value < 0 ? MINUS_SIGN : '';
return iso(`${sign}${number(Math.abs(value), decimals)}`);
}
/** `62.86` → `62٫9٪`. The value is already a percentage, not a fraction. */
export function percent(value: number, decimals = 1): string {
return `${number(value, decimals)}${PERCENT_SIGN}`;
}
/** `4` → `+4٫0٪` inside an LTR isolate. */
export function signedPercent(value: number, decimals = 1): string {
const sign = value > 0 ? '+' : value < 0 ? MINUS_SIGN : '';
return iso(`${sign}${number(Math.abs(value), decimals)}${PERCENT_SIGN}`);
}
/** `1 : 2٫8` inside an LTR isolate. */
export function ratio(a: number, b: number, decimals = 1): string {
return iso(`${number(a)} : ${number(b, decimals)}`);
}
/** Shamsi date in Tehran time: `15 خرداد 1404، ساعت 14:30`, or `15 خرداد 1404` with `{ time: false }`. */
export function date(
value: DateInput,
{ time = true }: DateFormatOptions = {},
): string {
const at = toDate(value);
if (!time) return dateFormatter.format(at);
// CLDR joins date and time with « ساعت »; the product style adds the Persian comma before it.
const parts = dateTimeFormatter.formatToParts(at);
const hourIndex = parts.findIndex((part) => part.type === 'hour');
const datePart = parts
.slice(0, hourIndex - 1)
.map((part) => part.value)
.join('');
const joiner = parts[hourIndex - 1]?.value.trim() ?? '';
const timePart = parts
.slice(hourIndex)
.map((part) => part.value)
.join('');
return `${datePart}، ${joiner} ${timePart}`;
}
/** `5 دقیقه پیش`, `2 ساعت پیش`, `دیروز`; older than a day → `date()`. */
export function relative(
value: DateInput,
now: DateInput = Date.now(),
): string {
const at = toDate(value);
const diff = toDate(now).getTime() - at.getTime();
if (diff < MINUTE_MS) return relativeFormatter.format(0, 'second');
if (diff < HOUR_MS)
return relativeFormatter.format(-Math.floor(diff / MINUTE_MS), 'minute');
if (diff < DAY_MS)
return relativeFormatter.format(-Math.floor(diff / HOUR_MS), 'hour');
if (diff < 2 * DAY_MS) return relativeFormatter.format(-1, 'day');
return date(at);
}
/** `IR620120000000101234567890` → `IR62 0120 0000 0010 1234 5678 90`. */
export function sheba(
value: string,
{ prefix = true }: ShebaFormatOptions = {},
): string {
const digits = latinDigits(value).replace(/^IR/i, '').replace(/\D/g, '');
const grouped =
(prefix ? `IR${digits}` : digits).match(/.{1,4}/g)?.join(' ') ?? '';
return grouped;
}