From 665734b1689518215c4939efa49f9ba174bce508 Mon Sep 17 00:00:00 2001 From: Krishna Acondy Date: Thu, 6 May 2021 13:59:33 +0100 Subject: [PATCH] chore(*): add tests --- src/utils/convertToCsv.spec.ts | 32 ++++++++++++++++++++++++++++++++ src/utils/convertToCsv.ts | 33 +++++++++------------------------ 2 files changed, 41 insertions(+), 24 deletions(-) diff --git a/src/utils/convertToCsv.spec.ts b/src/utils/convertToCsv.spec.ts index e1f8f85..aad5146 100644 --- a/src/utils/convertToCsv.spec.ts +++ b/src/utils/convertToCsv.spec.ts @@ -40,4 +40,36 @@ describe('convertToCsv', () => { expect(convertToCSV(data)).toEqual(expectedOutput) }) + + it('should convert values with mixed quotes', () => { + const data = [{ foo: `',''`, bar: `","` }] + + const expectedOutput = `foo:$4. bar:$3.\r\n"',''",""","""` + + expect(convertToCSV(data)).toEqual(expectedOutput) + }) + + it('should convert values with mixed quotes', () => { + const data = [{ foo: `','`, bar: `,"` }] + + const expectedOutput = `foo:$3. bar:$2.\r\n"','",","""` + + expect(convertToCSV(data)).toEqual(expectedOutput) + }) + + it('should convert values with mixed quotes', () => { + const data = [{ foo: `"`, bar: `'` }] + + const expectedOutput = `foo:$1. bar:$1.\r\n"""","'"` + + expect(convertToCSV(data)).toEqual(expectedOutput) + }) + + it('should convert values with mixed quotes', () => { + const data = [{ foo: `,`, bar: `',` }] + + const expectedOutput = `foo:$1. bar:$2.\r\n",","',"` + + expect(convertToCSV(data)).toEqual(expectedOutput) + }) }) diff --git a/src/utils/convertToCsv.ts b/src/utils/convertToCsv.ts index c071ffa..d6d0841 100644 --- a/src/utils/convertToCsv.ts +++ b/src/utils/convertToCsv.ts @@ -69,35 +69,20 @@ export const convertToCSV = (data: any) => { csvTest = data.map((row: any) => { const fields = Object.keys(row).map((fieldName, index) => { let value - let containsSpecialChar = false const currentCell = row[fieldName] - if (JSON.stringify(currentCell).search(/(\\t|\\n|\\r)/gm) > -1) { - containsSpecialChar = true - } - - value = JSON.stringify(currentCell, replacer) + // stringify with replacer converts null values to empty strings + // also wraps the value in double quotes + value = JSON.stringify(currentCell, replacer).replace(/\\\"/g, `""`) value = value.replace(/\\\\/gm, '\\') - if (containsSpecialChar) { - if (value.includes(',') || value.includes('"')) { - value = '"' + value + '"' - } - } else { - if ( - !value.includes(',') && - value.includes('"') && - !value.includes('\\"') - ) { - value = value.substring(1, value.length - 1) - } - - if (value.includes("'")) { - value = '"' + value + '"' - } - - value = value.replace(/\\"/gm, '""') + if ( + value.substring(1, value.length - 1).search(/(\\t|\\n|\\r|,|\'|\")/gm) < + 0 + ) { + // Remove wrapping quotes for values that don't contain special characters + value = value.substring(1, value.length - 1) } value = value.replace(/\r\n/gm, '\n')