Reorganize repo structure and standards references
This commit is contained in:
1 parent
3cb93a81be
commit
be2054274d
5885 files changed
+2588
-195
No files matched your search
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { getCachedFormatter } from "./cache.js";
|
||||
|
||||
describe("getCachedFormatter", () => {
|
||||
it("reuses formatters for equivalent option objects", () => {
|
||||
const cache = new Map<string, { readonly id: number }>();
|
||||
const create = vi.fn(() => ({ id: create.mock.calls.length + 1 }));
|
||||
|
||||
const first = getCachedFormatter(cache, "de-DE", { style: "currency", currency: "EUR", unused: undefined }, create);
|
||||
const second = getCachedFormatter(cache, "de-DE", { currency: "EUR", style: "currency" }, create);
|
||||
|
||||
expect(second).toBe(first);
|
||||
expect(create).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("evicts the oldest formatter after the bounded cache fills", () => {
|
||||
const cache = new Map<string, { readonly locale: string }>();
|
||||
const create = vi.fn((locale: string) => ({ locale }));
|
||||
|
||||
for (let index = 0; index < 130; index += 1) {
|
||||
getCachedFormatter(cache, `x-${index}`, {}, create);
|
||||
}
|
||||
|
||||
expect(cache.size).toBe(128);
|
||||
expect(cache.has("x-0|[]")).toBe(false);
|
||||
expect(cache.has("x-129|[]")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
const MAX_FORMATTER_CACHE_SIZE = 128;
|
||||
|
||||
export function getCachedFormatter<TFormatter>(
|
||||
cache: Map<string, TFormatter>,
|
||||
locale: string,
|
||||
options: Record<string, unknown>,
|
||||
create: (locale: string, options: Record<string, unknown>) => TFormatter
|
||||
): TFormatter {
|
||||
const key = `${locale}|${stableOptionsKey(options)}`;
|
||||
const cached = cache.get(key);
|
||||
if (cached) return cached;
|
||||
|
||||
const formatter = create(locale, options);
|
||||
if (cache.size >= MAX_FORMATTER_CACHE_SIZE) {
|
||||
const oldestKey = cache.keys().next().value;
|
||||
if (oldestKey) cache.delete(oldestKey);
|
||||
}
|
||||
cache.set(key, formatter);
|
||||
return formatter;
|
||||
}
|
||||
|
||||
function stableOptionsKey(options: Record<string, unknown>): string {
|
||||
return JSON.stringify(
|
||||
Object.entries(options)
|
||||
.filter(([, value]) => value !== undefined)
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { formatCurrency } from "./currency.js";
|
||||
|
||||
// String comparisons normalise whitespace because the ICU output uses U+00A0
|
||||
// (NBSP) between digits and the currency symbol — depending on Node/ICU
|
||||
// versions the *exact* code point can shift between regular space and NBSP.
|
||||
// We only assert on the digits + currency token to keep the test stable.
|
||||
function normalise(value: string) {
|
||||
return value.replace(/\s+/g, " ");
|
||||
}
|
||||
|
||||
describe("formatCurrency", () => {
|
||||
test("renders EUR in German format", () => {
|
||||
expect(normalise(formatCurrency(1234.5, { locale: "de-DE", currency: "EUR" }))).toBe("1.234,50 €");
|
||||
});
|
||||
|
||||
test("renders USD in English format", () => {
|
||||
expect(normalise(formatCurrency(1234.5, { locale: "en-US", currency: "USD" }))).toBe("$1,234.50");
|
||||
});
|
||||
|
||||
test("respects minimumFractionDigits", () => {
|
||||
const out = normalise(formatCurrency(10, { locale: "en-US", currency: "USD", minimumFractionDigits: 0 }));
|
||||
expect(out).toBe("$10");
|
||||
});
|
||||
|
||||
test("renders JPY without decimals by default", () => {
|
||||
expect(normalise(formatCurrency(1500, { locale: "ja-JP", currency: "JPY" }))).toBe("¥1,500");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
// Locale-aware currency formatter. Currency code is required (ISO-4217) so
|
||||
// callers cannot accidentally render an amount without the symbol — matches
|
||||
// billing/invoice surfaces that always know their currency.
|
||||
|
||||
import { getCachedFormatter } from "./cache.js";
|
||||
|
||||
export type FormatCurrencyOptions = {
|
||||
locale: string;
|
||||
currency: string;
|
||||
minimumFractionDigits?: number;
|
||||
maximumFractionDigits?: number;
|
||||
currencyDisplay?: Intl.NumberFormatOptions["currencyDisplay"];
|
||||
};
|
||||
|
||||
const currencyFormatters = new Map<string, Intl.NumberFormat>();
|
||||
|
||||
export function formatCurrency(value: number, options: FormatCurrencyOptions): string {
|
||||
const { locale, currency, ...rest } = options;
|
||||
return getCachedFormatter(currencyFormatters, locale, { style: "currency", currency, ...rest }, (formatterLocale, formatterOptions) => new Intl.NumberFormat(formatterLocale, formatterOptions)).format(value);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { formatDate, formatRelativeTime } from "./date.js";
|
||||
|
||||
describe("formatDate", () => {
|
||||
test("renders an ISO date per locale", () => {
|
||||
const out = formatDate("2026-05-17T12:00:00Z", { locale: "en-GB", timeZone: "UTC" });
|
||||
expect(out).toBe("17/05/2026");
|
||||
});
|
||||
|
||||
test("supports DateTimeFormat options", () => {
|
||||
const out = formatDate("2026-05-17T12:00:00Z", { locale: "de-DE", year: "numeric", month: "long", day: "numeric", timeZone: "UTC" });
|
||||
expect(out).toBe("17. Mai 2026");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatRelativeTime", () => {
|
||||
test("renders 'X days ago' for English", () => {
|
||||
const now = new Date("2026-05-17T12:00:00Z");
|
||||
const earlier = new Date("2026-05-14T12:00:00Z");
|
||||
expect(formatRelativeTime(earlier, { locale: "en-US", relativeTo: now, numeric: "always" })).toBe("3 days ago");
|
||||
});
|
||||
|
||||
test("renders 'vor X Tagen' for German", () => {
|
||||
const now = new Date("2026-05-17T12:00:00Z");
|
||||
const earlier = new Date("2026-05-14T12:00:00Z");
|
||||
expect(formatRelativeTime(earlier, { locale: "de-DE", relativeTo: now, numeric: "always" })).toBe("vor 3 Tagen");
|
||||
});
|
||||
|
||||
test("auto-derives the largest unit (minutes vs hours)", () => {
|
||||
const now = new Date("2026-05-17T12:00:00Z");
|
||||
const earlier = new Date("2026-05-17T11:00:00Z");
|
||||
expect(formatRelativeTime(earlier, { locale: "en-US", relativeTo: now, numeric: "always" })).toBe("1 hour ago");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
// Locale-aware date formatters. Provides both absolute (`formatDate`) and
|
||||
// relative (`formatRelativeTime`) variants — relative-time auto-derives the
|
||||
// largest sensible unit (years > months > days > hours > minutes > seconds).
|
||||
|
||||
import { getCachedFormatter } from "./cache.js";
|
||||
|
||||
export type FormatDateOptions = Intl.DateTimeFormatOptions & { locale: string };
|
||||
|
||||
const dateFormatters = new Map<string, Intl.DateTimeFormat>();
|
||||
const relativeTimeFormatters = new Map<string, Intl.RelativeTimeFormat>();
|
||||
|
||||
export function formatDate(value: Date | number | string, options: FormatDateOptions): string {
|
||||
const { locale, ...rest } = options;
|
||||
const date = value instanceof Date ? value : new Date(value);
|
||||
return getCachedFormatter(dateFormatters, locale, rest, (formatterLocale, formatterOptions) => new Intl.DateTimeFormat(formatterLocale, formatterOptions)).format(date);
|
||||
}
|
||||
|
||||
export type FormatRelativeTimeOptions = {
|
||||
locale: string;
|
||||
relativeTo?: Date | number;
|
||||
numeric?: Intl.RelativeTimeFormatOptions["numeric"];
|
||||
style?: Intl.RelativeTimeFormatOptions["style"];
|
||||
};
|
||||
|
||||
const RELATIVE_UNITS: Array<{ unit: Intl.RelativeTimeFormatUnit; ms: number }> = [
|
||||
{ unit: "year", ms: 365.25 * 24 * 60 * 60 * 1000 },
|
||||
{ unit: "month", ms: 30 * 24 * 60 * 60 * 1000 },
|
||||
{ unit: "day", ms: 24 * 60 * 60 * 1000 },
|
||||
{ unit: "hour", ms: 60 * 60 * 1000 },
|
||||
{ unit: "minute", ms: 60 * 1000 },
|
||||
{ unit: "second", ms: 1000 },
|
||||
];
|
||||
|
||||
export function formatRelativeTime(value: Date | number | string, options: FormatRelativeTimeOptions): string {
|
||||
const { locale, relativeTo, numeric = "auto", style = "long" } = options;
|
||||
const target = value instanceof Date ? value.getTime() : new Date(value).getTime();
|
||||
const anchor = relativeTo instanceof Date ? relativeTo.getTime() : typeof relativeTo === "number" ? relativeTo : Date.now();
|
||||
const delta = target - anchor;
|
||||
const formatter = getCachedFormatter(
|
||||
relativeTimeFormatters,
|
||||
locale,
|
||||
{ numeric, style },
|
||||
(formatterLocale, formatterOptions) => new Intl.RelativeTimeFormat(formatterLocale, formatterOptions)
|
||||
);
|
||||
for (const { unit, ms } of RELATIVE_UNITS) {
|
||||
if (Math.abs(delta) >= ms || unit === "second") {
|
||||
return formatter.format(Math.round(delta / ms), unit);
|
||||
}
|
||||
}
|
||||
return formatter.format(0, "second");
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// Barrel for the locale-aware Intl-API wrappers. All helpers are pure +
|
||||
// SSR-safe (no DOM access) and accept an explicit `locale` so server code can
|
||||
// render exactly what the client sees.
|
||||
|
||||
export { formatNumber, formatPercent, formatCompactNumber, type FormatNumberOptions } from "./number.js";
|
||||
export { formatCurrency, type FormatCurrencyOptions } from "./currency.js";
|
||||
export { formatDate, formatRelativeTime, type FormatDateOptions, type FormatRelativeTimeOptions } from "./date.js";
|
||||
export { formatList, type FormatListOptions } from "./list.js";
|
||||
@@ -0,0 +1,16 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { formatList } from "./list.js";
|
||||
|
||||
describe("formatList", () => {
|
||||
test("joins with 'and' for English conjunction", () => {
|
||||
expect(formatList(["Alpha", "Bravo", "Charlie"], { locale: "en-US" })).toBe("Alpha, Bravo, and Charlie");
|
||||
});
|
||||
|
||||
test("joins with 'und' for German conjunction", () => {
|
||||
expect(formatList(["Alpha", "Bravo", "Charlie"], { locale: "de-DE" })).toBe("Alpha, Bravo und Charlie");
|
||||
});
|
||||
|
||||
test("supports disjunction", () => {
|
||||
expect(formatList(["Alpha", "Bravo"], { locale: "en-US", type: "disjunction" })).toBe("Alpha or Bravo");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
// Locale-aware list join (Oxford-comma/und-style). Wraps `Intl.ListFormat`.
|
||||
|
||||
import { getCachedFormatter } from "./cache.js";
|
||||
|
||||
export type FormatListOptions = {
|
||||
locale: string;
|
||||
type?: Intl.ListFormatOptions["type"];
|
||||
style?: Intl.ListFormatOptions["style"];
|
||||
};
|
||||
|
||||
const listFormatters = new Map<string, Intl.ListFormat>();
|
||||
|
||||
export function formatList(items: readonly string[], options: FormatListOptions): string {
|
||||
const { locale, type = "conjunction", style = "long" } = options;
|
||||
return getCachedFormatter(listFormatters, locale, { type, style }, (formatterLocale, formatterOptions) => new Intl.ListFormat(formatterLocale, formatterOptions)).format(items);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { formatCompactNumber, formatNumber, formatPercent } from "./number.js";
|
||||
|
||||
describe("formatNumber", () => {
|
||||
test("formats decimals per locale", () => {
|
||||
expect(formatNumber(1234.5, { locale: "de-DE" })).toBe("1.234,5");
|
||||
expect(formatNumber(1234.5, { locale: "en-US" })).toBe("1,234.5");
|
||||
});
|
||||
|
||||
test("respects fraction digits", () => {
|
||||
expect(formatNumber(1, { locale: "en-US", minimumFractionDigits: 2 })).toBe("1.00");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatPercent", () => {
|
||||
test("renders a percent sign per locale", () => {
|
||||
expect(formatPercent(0.25, { locale: "en-US" })).toBe("25%");
|
||||
// German uses non-breaking space U+00A0 between number and sign.
|
||||
expect(formatPercent(0.25, { locale: "de-DE" })).toBe("25 %");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatCompactNumber", () => {
|
||||
test("collapses large numbers", () => {
|
||||
expect(formatCompactNumber(1500, { locale: "en-US" })).toBe("1.5K");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
// Locale-aware number formatter wrapping `Intl.NumberFormat`. Centralised so
|
||||
// every callsite shares a single contract — decimal/percent/compact derive
|
||||
// from this helper to avoid drift between server/client.
|
||||
|
||||
import { getCachedFormatter } from "./cache.js";
|
||||
|
||||
export type FormatNumberOptions = Intl.NumberFormatOptions & { locale: string };
|
||||
|
||||
const numberFormatters = new Map<string, Intl.NumberFormat>();
|
||||
|
||||
export function formatNumber(value: number, options: FormatNumberOptions): string {
|
||||
const { locale, ...rest } = options;
|
||||
return getCachedFormatter(numberFormatters, locale, rest, (formatterLocale, formatterOptions) => new Intl.NumberFormat(formatterLocale, formatterOptions)).format(value);
|
||||
}
|
||||
|
||||
export function formatPercent(value: number, options: FormatNumberOptions): string {
|
||||
const { locale, ...rest } = options;
|
||||
return getCachedFormatter(numberFormatters, locale, { style: "percent", ...rest }, (formatterLocale, formatterOptions) => new Intl.NumberFormat(formatterLocale, formatterOptions)).format(value);
|
||||
}
|
||||
|
||||
export function formatCompactNumber(value: number, options: FormatNumberOptions): string {
|
||||
const { locale, ...rest } = options;
|
||||
return getCachedFormatter(numberFormatters, locale, { notation: "compact", ...rest }, (formatterLocale, formatterOptions) => new Intl.NumberFormat(formatterLocale, formatterOptions)).format(value);
|
||||
}
|
||||
Reference in new issue
Block a user