Open History to see the last commit
1import { mFallback, msg } from "gt-i18n";
2import type { M } from "gt-i18n";
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: M = 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({ context: "list of two" })`${{ first: items[0]! }} and ${{ second: items[1]! }}`,
17 );
18 }
19 let list = resolve(
20 msg({
21 context: "last two items of a list of three or more",
22 })`${{ first: items.at(-2)! }}, and ${{ last: items.at(-1)! }}`,
23 );
24 for (let index = items.length - 3; index >= 0; index -= 1) {
25 list = resolve(
26 msg({
27 context: "an item followed by the rest of a list",
28 })`${{ first: items[index]! }}, ${{ rest: list }}`,
29 );
30 }
31 return list;
32}