Skip to content

Commit fa8e132

Browse files
author
Scover
committed
fixed csv escaping logic
1 parent 8301c6a commit fa8e132

File tree

2 files changed

+44
-9
lines changed

2 files changed

+44
-9
lines changed

src/handlers/csv.ts

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,5 @@
1-
// future implementation of json converison
2-
// todo:
3-
// - implement format handler
4-
// - finish writing pr
5-
61
import CommonFormats from 'src/CommonFormats.ts';
7-
import { FormatDefinition, type FileData, type FileFormat, type FormatHandler } from '../FormatHandler.ts';
2+
import { type FileData, type FileFormat, type FormatHandler } from '../FormatHandler.ts';
83

94
export type Flat = { header: string[]; data: string[][] };
105
type SolverState = { rows: number; cols: number; K: number[] };
@@ -42,9 +37,10 @@ export default class csvHandler implements FormatHandler {
4237
}
4338

4439
export function toCsv(x: Flat, sep = ',', quot = '"') {
45-
function csvrow(arr: string[]) {
46-
return arr.map(x => (x.includes(sep) ? `${quot}${sep.replace(quot, quot + quot)}${quot}` : x)).join(sep);
47-
}
40+
const csvrow = (arr: string[]) =>
41+
arr
42+
.map(s => (s.includes(sep) || s.includes(quot) ? `${quot}${s.replaceAll(quot, quot + quot)}${quot}` : s))
43+
.join(sep);
4844
return [x.header, ...x.data].map(row => csvrow(row)).join('\n');
4945
}
5046

test/handlers/csv.test.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1171,5 +1171,44 @@ A.C,1,1
11711171
,1
11721172
,1`,
11731173
],
1174+
[
1175+
'csv escaping comma',
1176+
{
1177+
plain: 'alpha',
1178+
comma: 'hello,world',
1179+
nested: {
1180+
value: 'a,b',
1181+
},
1182+
},
1183+
{
1184+
header: ['key', 'value'],
1185+
data: [
1186+
['plain', 'alpha'],
1187+
['comma', 'hello,world'],
1188+
['nested.value', 'a,b'],
1189+
],
1190+
},
1191+
`key,value
1192+
plain,alpha
1193+
comma,"hello,world"
1194+
nested.value,"a,b"`,
1195+
],
1196+
[
1197+
'csv escaping quotes',
1198+
{
1199+
quote: 'say "hi"',
1200+
both: 'x, "y"',
1201+
},
1202+
{
1203+
header: ['key', 'value'],
1204+
data: [
1205+
['quote', 'say "hi"'],
1206+
['both', 'x, "y"'],
1207+
],
1208+
},
1209+
`key,value
1210+
quote,"say ""hi"""
1211+
both,"x, ""y"""`,
1212+
],
11741213
];
11751214
}

0 commit comments

Comments
 (0)