1
10
11const MAX_CELLS_PER_ROW = 1000;
12
13export function parseCsv(input: string): string[][] {
14
15 const text = input.charCodeAt(0) === 0xfeff ? input.slice(1) : input;
16 const rows: string[][] = [];
17 let row: string[] = [];
18 let cell = "";
19 let inQuotes = false;
20
21 for (let i = 0; i < text.length; i += 1) {
22 const c = text[i];
23 if (inQuotes) {
24 if (c === '"') {
25 if (text[i + 1] === '"') {
26 cell += '"';
27 i += 1;
28 } else {
29 inQuotes = false;
30 }
31 } else {
32 cell += c;
33 }
34 continue;
35 }
36 if (c === '"') {
37 inQuotes = true;
38 } else if (c === ",") {
39 row.push(cell);
40 cell = "";
41 } else if (c === "\n" || c === "\r") {
42 if (c === "\r" && text[i + 1] === "\n") i += 1;
43 row.push(cell);
44 cell = "";
45 rows.push(row);
46 row = [];
47 } else {
48 cell += c;
49 }
50 }
51
52 if (cell.length > 0 || row.length > 0) {
53 row.push(cell);
54 rows.push(row);
55 }
56
57 return rows.map((r) => (r.length > MAX_CELLS_PER_ROW ? r.slice(0, MAX_CELLS_PER_ROW) : r));
58}
59