/** * cache ตัว formatter ของ Intl — constructor ของ Intl.NumberFormat/DateTimeFormat แพง (โหลดข้อมูล locale) * ตารางที่มีเซลล์ตัวเลข/วันที่หลายร้อยช่องจะสร้างซ้ำทุกเซลล์ทุก render ถ้าไม่ cache * key = locale + options (JSON) — options ของเราเป็น object เล็ก ๆ ไม่มี key แปลก */ const numberFormats = new Map(); const dateTimeFormats = new Map(); const relativeTimeFormats = new Map(); function keyOf(locale: string, options: object | undefined): string { return `${locale}|${options ? JSON.stringify(options) : ""}`; } export function getNumberFormat(locale: string, options?: Intl.NumberFormatOptions) { const key = keyOf(locale, options); let f = numberFormats.get(key); if (!f) { f = new Intl.NumberFormat(locale, options); numberFormats.set(key, f); } return f; } /** วันที่สัมพัทธ์ ("เมื่อวาน", "ในอีก 3 วัน") — ใช้ในเซลล์ตาราง/รายการยาวทุกแถว จึงเก็บไว้ใช้ซ้ำ */ export function getRelativeTimeFormat(locale: string, options?: Intl.RelativeTimeFormatOptions) { const key = keyOf(locale, options); let f = relativeTimeFormats.get(key); if (!f) { f = new Intl.RelativeTimeFormat(locale, options); relativeTimeFormats.set(key, f); } return f; } export function getDateTimeFormat(locale: string, options?: Intl.DateTimeFormatOptions) { const key = keyOf(locale, options); let f = dateTimeFormats.get(key); if (!f) { f = new Intl.DateTimeFormat(locale, options); dateTimeFormats.set(key, f); } return f; }