Open History to see the last commit
1import { mFallback, msg } from "gt-i18n";
2import type { MFunctionType } from "gt-i18n/types";
3
4/** "A, B, and C" in `locale`. Hermes ships without Intl.ListFormat, so it joins with `resolve`. */
5export function formatConjunctionList(
6 items: ReadonlyArray<string>,
7 locale: string,
8 resolve: MFunctionType = mFallback,
9): string {
10 if (typeof Intl.ListFormat === "function") {
11 return new Intl.ListFormat(locale, { type: "conjunction" }).format(items);
12 }
13 if (items.length <= 1) return items[0] ?? "";
14 if (items.length === 2) {
15 return resolve(
16 msg("{first} and {second}", { first: items[0]!, second: items[1]!, $context: "list of two" }),
17 );
18 }
19 let list = resolve(
20 msg("{first}, and {last}", {
21 first: items.at(-2)!,
22 last: items.at(-1)!,
23 $context: "last two items of a list of three or more",
24 }),
25 );
26 for (let index = items.length - 3; index >= 0; index -= 1) {
27 list = resolve(
28 msg("{first}, {rest}", {
29 first: items[index]!,
30 rest: list,
31 $context: "an item followed by the rest of a list",
32 }),
33 );
34 }
35 return list;
36}