-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreadable-string-list.ts
58 lines (53 loc) · 2.01 KB
/
readable-string-list.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Please refer to the terms of the license agreement in the root of the project
*
* (c) 2024 Feedzai
*/
// eslint-disable-next-line @typescript-eslint/no-namespace
declare namespace Intl {
type ListType = "conjunction" | "disjunction";
interface ListFormatOptions {
localeMatcher?: "lookup" | "best fit";
type?: ListType;
style?: "long" | "short" | "narrow";
}
interface ListFormatPart {
type: "element" | "literal";
value: string;
}
class ListFormat {
constructor(locales?: string | string[], options?: ListFormatOptions);
format(values: any[]): string;
formatToParts(values: any[]): ListFormatPart[];
supportedLocalesOf(locales: string | string[], options?: ListFormatOptions): string[];
}
}
/**
* Enables language-sensitive list formatting.
*
* @example
*
* const Simpsons = ["Homer", "Marge", "Lisa", "Bart", "Maggie"];
*
* readableStringList(Simpsons, "en", "and"); // 'Homer, Marge, Lisa, Bart and Maggie'
* readableStringList(Simpsons, "pt", "and"); // 'Homer, Marge, Lisa, Bart e Maggie'
* readableStringList(Simpsons, "fr", "and"); // 'Homer, Marge, Lisa, Bart et Maggie'
* readableStringList(Simpsons, "de", "and"); // 'Homer, Marge, Lisa, Bart und Maggie'
*
* readableStringList(Simpsons, "en", "or"); // 'Homer, Marge, Lisa, Bart or Maggie'
* readableStringList(Simpsons, "pt", "or"); // 'Homer, Marge, Lisa, Bart ou Maggie'
* readableStringList(Simpsons, "fr", "or"); // 'Homer, Marge, Lisa, Bart our Maggie'
* readableStringList(Simpsons, "de", "or"); // 'Homer, Marge, Lisa, Bart oder Maggie'
*
* @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat Intl.ListFormat
*
* @param {string[]} source
* @param {string} [locale="en"]
* @param {("and" | "or")} [type="and"]
* @returns {string}
*/
export function readableStringList(source: string[], locale = "en", type: "and" | "or" = "and") {
return new Intl.ListFormat(locale, {
type: type === "and" ? "conjunction" : "disjunction",
}).format(source);
}