Skip to content

Commit 1c75f4f

Browse files
committed
Extend joinAnd with oxfordComma option
1 parent 6a919cc commit 1c75f4f

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

src/text.ts

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,24 @@ export function truncateWithEllipsis(str: string, length: number) {
66
}
77
}
88

9-
export function joinAnd(val: string[], initialSep = ', ', finalSep = ' and ') {
9+
export function joinAnd(val: string[], options: {
10+
// Separator between all but the last value
11+
separator?: string,
12+
// Separator before last value (preceeded with space or `separator` if oxfordComma is true)
13+
finalSeparator?: string,
14+
// Should there be a separator between the penultimate value & finalSeparator?
15+
oxfordComma?: boolean
16+
} = {}) {
1017
if (val.length === 1) return val[0];
1118

12-
return val.slice(0, -1).join(initialSep) + finalSep + val[val.length - 1];
19+
const separator = options.separator ?? ', ';
20+
const finalSeparator = options.finalSeparator ?? 'and ';
21+
const oxfordComma = options.oxfordComma ?? false;
22+
23+
return val.slice(0, -1).join(separator) +
24+
(oxfordComma ? separator : ' ') +
25+
finalSeparator +
26+
val[val.length - 1];
1327
}
1428

1529
const VOWEL_ISH = ['a', 'e', 'i', 'o', 'u', 'y'];

0 commit comments

Comments
 (0)