1
- const defaults = {
2
- separator : '' ,
3
- conjunction : '' ,
4
- serial : false ,
5
- } ;
6
-
7
1
/**
8
2
* Converts an array substitution to a string containing a list
9
3
* @param {String } [opts.separator = ''] - the character that separates each item
@@ -12,34 +6,31 @@ const defaults = {
12
6
*
13
7
* @return {Object } - a TemplateTag transformer
14
8
*/
15
- const inlineArrayTransformer = ( opts = defaults ) => ( {
9
+ const inlineArrayTransformer = ( {
10
+ conjunction = '' ,
11
+ separator = '' ,
12
+ serial = false ,
13
+ } = { } ) => ( {
16
14
onSubstitution ( substitution , resultSoFar ) {
17
15
// only operate on arrays
18
- if ( Array . isArray ( substitution ) ) {
19
- const arrayLength = substitution . length ;
20
- const separator = opts . separator ;
21
- const conjunction = opts . conjunction ;
22
- const serial = opts . serial ;
23
- // join each item in the array into a string where each item is separated by separator
24
- // be sure to maintain indentation
25
- const indent = resultSoFar . match ( / ( \n ? [ ^ \S \n ] + ) $ / ) ;
26
- if ( indent ) {
27
- substitution = substitution . join ( separator + indent [ 1 ] ) ;
28
- } else {
29
- substitution = substitution . join ( separator + ' ' ) ;
30
- }
31
- // if conjunction is set, replace the last separator with conjunction, but only if there is more than one substitution
32
- if ( conjunction && arrayLength > 1 ) {
33
- const separatorIndex = substitution . lastIndexOf ( separator ) ;
34
- substitution =
35
- substitution . slice ( 0 , separatorIndex ) +
36
- ( serial ? separator : '' ) +
37
- ' ' +
38
- conjunction +
39
- substitution . slice ( separatorIndex + 1 ) ;
40
- }
16
+ if ( ! Array . isArray ( substitution ) ) {
17
+ return substitution ;
41
18
}
42
- return substitution ;
19
+
20
+ // be sure to maintain indentation
21
+ const indent = resultSoFar . match ( / ( \n ? [ ^ \S \n ] + ) $ / ) ;
22
+ const fullSeparator = separator . concat ( indent ? indent [ 1 ] : ' ' ) ;
23
+ const fullConjunction = '' . concat ( conjunction , ' ' ) ;
24
+ const conjunctionIndex = conjunction ? substitution . length - 1 : - 1 ;
25
+
26
+ return substitution . reduce ( ( result , part , index ) =>
27
+ '' . concat (
28
+ result ,
29
+ index !== conjunctionIndex || serial ? fullSeparator : ' ' ,
30
+ index === conjunctionIndex ? fullConjunction : '' ,
31
+ part ,
32
+ ) ,
33
+ ) ;
43
34
} ,
44
35
} ) ;
45
36
0 commit comments