-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcsv.ts
40 lines (37 loc) · 829 Bytes
/
csv.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import * as $ from "../mod.ts";
const comma = $.token(",");
const dquote = $.token('"');
const escapedDquote = $.token('""');
const textdata = $.regex(/[^,\r\n"]+/);
const eol = $.choice($.token("\r\n"), $.token("\n"));
const nonEscaped = textdata;
const escaped = $.map(
$.seq(
dquote,
$.many(
$.choice(
textdata,
eol,
comma,
$.map(escapedDquote, () => {
return '"';
})
)
),
dquote
),
result => {
return result[1].join("");
}
);
const field = $.choice(nonEscaped, escaped);
const record = $.sepBy(field, comma);
const file = $.sepBy(record, eol);
export function parseCsv(src: string) {
const result = file(src, 0);
//Parse Error
if (!result[0]) {
return [];
}
return result[1];
}