/
formatName.ts
35 lines (31 loc) · 976 Bytes
/
formatName.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
import {FAMILY_NAME_GIVEN_NAME_ORDERING_INDEXED_BY_LANGUAGE} from './constants';
import {languageFromLocale} from './utilities';
// Note: A similar Ruby implementation of this function also exists at https://github.com/Shopify/shopify-i18n/blob/main/lib/shopify-i18n/name_formatter.rb.
export function formatName({
name,
locale,
options,
}: {
name: {givenName?: string; familyName?: string};
locale: string;
options?: {full?: boolean};
}) {
if (!name.givenName) {
return name.familyName || '';
}
if (!name.familyName) {
return name.givenName;
}
const isFullName = Boolean(options && options.full);
const customNameFormatter =
FAMILY_NAME_GIVEN_NAME_ORDERING_INDEXED_BY_LANGUAGE.get(
languageFromLocale(locale),
);
if (customNameFormatter) {
return customNameFormatter(name.givenName, name.familyName, isFullName);
}
if (isFullName) {
return `${name.givenName} ${name.familyName}`;
}
return name.givenName;
}