Skip to content

Commit a3aa307

Browse files
committed
[#21] Added a missing test
1 parent 4dd12e4 commit a3aa307

File tree

2 files changed

+31
-5
lines changed

2 files changed

+31
-5
lines changed

src/lib/field-stringifier.ts

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff 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

2028
class 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

3240
class 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

src/test/field-stringifier.test.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff 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 () => {

0 commit comments

Comments
 (0)