File tree Expand file tree Collapse file tree 2 files changed +31
-5
lines changed Expand file tree Collapse file tree 2 files changed +31
-5
lines changed Original file line number Diff line number Diff line change @@ -15,13 +15,21 @@ export abstract class FieldStringifier {
1515 }
1616
1717 abstract stringify ( value ?: Field ) : string ;
18+
19+ protected isEmpty ( value ?: Field ) : boolean {
20+ return typeof value === 'undefined' || value === null || value === '' ;
21+ }
22+
23+ protected quoteField ( field : string ) : string {
24+ return `"${ field . replace ( / " / g, '""' ) } "` ;
25+ }
1826}
1927
2028class DefaultFieldStringifier extends FieldStringifier {
2129 stringify ( value ?: Field ) : string {
22- if ( typeof value === 'undefined' || value === null ) return '' ;
30+ if ( this . isEmpty ( value ) ) return '' ;
2331 const str = String ( value ) ;
24- return this . needsQuote ( str ) ? `" ${ str . replace ( / " / g , '""' ) } "` : str ;
32+ return this . needsQuote ( str ) ? this . quoteField ( str ) : str ;
2533 }
2634
2735 private needsQuote ( str : string ) : boolean {
@@ -31,9 +39,7 @@ class DefaultFieldStringifier extends FieldStringifier {
3139
3240class ForceQuoteFieldStringifier extends FieldStringifier {
3341 stringify ( value ?: Field ) : string {
34- if ( typeof value === 'undefined' || value === null ) return '' ;
35- const str = String ( value ) ;
36- return `"${ str . replace ( / " / g, '""' ) } "` ;
42+ return this . isEmpty ( value ) ? '' : this . quoteField ( String ( value ) ) ;
3743 }
3844}
3945
Original file line number Diff line number Diff line change @@ -8,6 +8,26 @@ describe('DefaultFieldStringifier', () => {
88
99 describe ( 'When field delimiter is semicolon' , generateTestCases ( ';' ) ) ;
1010
11+ describe ( 'When all fields needs to be quoted' , ( ) => {
12+ const stringifier = createFieldStringifier ( ',' , true ) ;
13+
14+ it ( 'quotes a field' , ( ) => {
15+ strictEqual ( stringifier . stringify ( 'VALUE' ) , '"VALUE"' ) ;
16+ } ) ;
17+
18+ it ( 'does not quote a field of value undefined' , ( ) => {
19+ strictEqual ( stringifier . stringify ( ) , '' ) ;
20+ } ) ;
21+
22+ it ( 'does not quote a field of value null' , ( ) => {
23+ strictEqual ( stringifier . stringify ( null ) , '' ) ;
24+ } ) ;
25+
26+ it ( 'does not quote a field of value empty string' , ( ) => {
27+ strictEqual ( stringifier . stringify ( '' ) , '' ) ;
28+ } ) ;
29+ } ) ;
30+
1131 function generateTestCases ( fieldDelimiter : string ) {
1232 const delim = resolveDelimiterChar ( fieldDelimiter ) ;
1333 return ( ) => {
You can’t perform that action at this time.
0 commit comments