返回 CodeWhale
plural.ts
根目录 / web / lib / i18n / plural.ts
1 export type PluralCategory = "zero" | "one" | "two" | "few" | "many" | "other";
2
3 export type PluralForms = Partial<Record<PluralCategory, string>> & { other: string };
4
5 export const PLURAL_CATEGORIES: readonly PluralCategory[] = ["zero", "one", "two", "few", "many", "other"];
6
7 export function pluralCategory(locale: string, n: number): PluralCategory {
8 try {
9 return new Intl.PluralRules(locale).select(n) as PluralCategory;
10 } catch {
11 return "other";
12 }
13 }
14
15 export function pluralText(forms: PluralForms, n: number, locale: string, numberLocale: string = locale): string {
16 const template = forms[pluralCategory(locale, n)] ?? forms.other;
17 let formatted: string;
18 try {
19 formatted = new Intl.NumberFormat(numberLocale).format(n);
20 } catch {
21 formatted = String(n);
22 }
23 return template.replace(/\{n\}/g, formatted);
24 }
25
26 export function pluralCategoriesFor(locale: string): PluralCategory[] {
27 const rules = new Intl.PluralRules(locale);
28 const reached = new Set<PluralCategory>(["other"]);
29 for (let n = 0; n <= 1000; n += 1) reached.add(rules.select(n) as PluralCategory);
30 return PLURAL_CATEGORIES.filter((category) => reached.has(category));
31 }
32
32 lines TYPESCRIPT