xref: /expo/packages/@expo/cli/src/utils/strings.ts (revision 6fb32ddd)
1*6fb32dddSKeith Kurak/**
2*6fb32dddSKeith Kurak * Joins strings with commas and 'and', based on English rules, limiting the number of items enumerated to keep from filling the console.
3*6fb32dddSKeith Kurak * @param items strings to join
4*6fb32dddSKeith Kurak * @param limit max number of strings to enumerate before using 'others'
5*6fb32dddSKeith Kurak * @returns joined string
6*6fb32dddSKeith Kurak */
7*6fb32dddSKeith Kurakexport function joinWithCommasAnd(items: string[], limit: number | undefined = 10): string {
8*6fb32dddSKeith Kurak  if (!items.length) {
9*6fb32dddSKeith Kurak    return '';
10*6fb32dddSKeith Kurak  }
11*6fb32dddSKeith Kurak
12*6fb32dddSKeith Kurak  const uniqueItems = items.filter((value, index, array) => array.indexOf(value) === index);
13*6fb32dddSKeith Kurak
14*6fb32dddSKeith Kurak  if (uniqueItems.length === 1) {
15*6fb32dddSKeith Kurak    return uniqueItems[0];
16*6fb32dddSKeith Kurak  }
17*6fb32dddSKeith Kurak
18*6fb32dddSKeith Kurak  if (limit && uniqueItems.length > limit) {
19*6fb32dddSKeith Kurak    const first = uniqueItems.slice(0, limit);
20*6fb32dddSKeith Kurak    const remaining = uniqueItems.length - limit;
21*6fb32dddSKeith Kurak    return `${first.join(', ')}, and ${remaining} ${remaining > 1 ? 'others' : 'other'}`;
22*6fb32dddSKeith Kurak  }
23*6fb32dddSKeith Kurak
24*6fb32dddSKeith Kurak  const last = uniqueItems.pop();
25*6fb32dddSKeith Kurak  return `${uniqueItems.join(', ')}${uniqueItems.length >= 2 ? ',' : ''} and ${last}`;
26*6fb32dddSKeith Kurak}
27