import { ARABIC_DIGITS, DATE_TIME_JOINER, DAY_MS, DECIMAL_SEPARATOR, HORIZON_UNITS, HOUR_MS, JUST_NOW, LESS_THAN, 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, DurationUnit, 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 timeFormatter = new Intl.DateTimeFormat(LOCALE, { timeZone: TIME_ZONE, hour: '2-digit', minute: '2-digit', hourCycle: 'h23', }); const relativeFormatter = new Intl.RelativeTimeFormat(LOCALE, { numeric: 'auto', }); const numberFormatters = new Map(); const unitFormatters = new Map(); /** `13 روز`: the unit word comes from CLDR, so it stays in step with the locale. */ function unitAmount(value: number, unit: DurationUnit): string { let formatter = unitFormatters.get(unit); if (!formatter) { formatter = new Intl.NumberFormat(LOCALE, { style: 'unit', unit, unitDisplay: 'long', }); unitFormatters.set(unit, formatter); } return formatter.format(value); } 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); }); } /** True when `value` shows as zero at `decimals`, so `-0.4` never prints as `−0`. */ function roundsToZero(value: number, decimals: number): boolean { return Number(Math.abs(value).toFixed(decimals)) === 0; } /** `+`, `−`, or nothing for a value that rounds to zero. */ function sign(value: number, decimals: number): string { if (roundsToZero(value, decimals)) return ''; return value > 0 ? '+' : MINUS_SIGN; } /** `1234567.8` → `1٬234٬567٫8`. The font draws the digits in Persian. */ export function number(value: number, decimals = 0): string { const digits = persianSeparators( numberFormatter(decimals).format(Math.abs(value)), ); return value < 0 && !roundsToZero(value, decimals) ? `${MINUS_SIGN}${digits}` : digits; } /** A price keeps the decimals it has, up to 6: `1.092` → `1٫092`. A missing price shows `—`. */ export function price(value: number | null | undefined): string { if (value == null || Number.isNaN(value)) return '—'; // Not toString(): it writes 1.2e-7 in exponent notation. const plain = value.toLocaleString('en-US', { useGrouping: false, maximumFractionDigits: 20, }); const decimals = Math.min(plain.split('.')[1]?.length ?? 0, 6); return number(value, decimals); } /** Shows `+` or `−` (none for zero), inside an LTR isolate: `−120٬000`. */ export function signed(value: number, decimals = 0): string { return iso(`${sign(value, decimals)}${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 (no sign for zero). */ export function signedPercent(value: number, decimals = 1): string { return iso( `${sign(value, decimals)}${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); const day = dateFormatter.format(at); return time ? `${day}${DATE_TIME_JOINER}${timeFormatter.format(at)}` : day; } /** `همین الان`, `5 دقیقه پیش`, `2 ساعت پیش`, `دیروز`; older than that → `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 JUST_NOW; 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`, grouped as banks print it. * `{ prefix: false }` drops `IR` and keeps the same groups: `62 0120 0000 …`. */ export function sheba( value: string, { prefix = true }: ShebaFormatOptions = {}, ): string { const digits = latinDigits(value).replace(/^IR/i, '').replace(/\D/g, ''); const grouped = `IR${digits}`.match(/.{1,4}/g)?.join(' ') ?? ''; return prefix ? grouped : grouped.slice(2); } /** * A span of time, for a prediction's holding time or time past its horizon: under an hour * `کمتر از 1 ساعت`, under 48 hours rounded hours (`5 ساعت`), then rounded days (`13 روز`). */ export function duration(ms: number): string { const hours = Math.max(0, ms) / HOUR_MS; if (hours < 1) return `${LESS_THAN} ${unitAmount(1, 'hour')}`; if (hours < 48) return unitAmount(Math.round(hours), 'hour'); return unitAmount(Math.round(hours / 24), 'day'); } /** A prediction's horizon as the API sends it: `3d` → `3 روز`, `2w` → `2 هفته`. Unknown input passes through. */ export function horizon(value: string): string { const match = /^(\d+)\s*([hdwmy])$/i.exec(value.trim()); if (!match) return value; const unit = HORIZON_UNITS[match[2].toLowerCase() as keyof typeof HORIZON_UNITS]; return unitAmount(Number(match[1]), unit); } /** Seconds as a countdown clock: `102` → `01:42`. Negative values show `00:00`. */ export function clock(totalSeconds: number): string { const seconds = Math.max(0, Math.ceil(totalSeconds)); const pad = (part: number) => String(part).padStart(2, '0'); return `${pad(Math.floor(seconds / 60))}:${pad(seconds % 60)}`; }