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