* Parse CSV string to table data
(csv: string)
| 14 | * Parse CSV string to table data |
| 15 | */ |
| 16 | function parseCsv(csv: string): { headers: string[]; rows: string[][] } { |
| 17 | const lines = csv.trim().split('\n') |
| 18 | if (lines.length === 0 || (lines.length === 1 && lines[0].trim() === '')) { |
| 19 | return { headers: ['Column 1'], rows: [] } |
| 20 | } |
| 21 | |
| 22 | const parseRow = (line: string): string[] => { |
| 23 | const cells: string[] = [] |
| 24 | let current = '' |
| 25 | let inQuotes = false |
| 26 | |
| 27 | for (let i = 0; i < line.length; i++) { |
| 28 | const char = line[i] |
| 29 | if (char === '"') { |
| 30 | if (inQuotes && line[i + 1] === '"') { |
| 31 | current += '"' |
| 32 | i++ |
| 33 | } else { |
| 34 | inQuotes = !inQuotes |
| 35 | } |
| 36 | } else if (char === ',' && !inQuotes) { |
| 37 | cells.push(current) |
| 38 | current = '' |
| 39 | } else { |
| 40 | current += char |
| 41 | } |
| 42 | } |
| 43 | cells.push(current) |
| 44 | return cells |
| 45 | } |
| 46 | |
| 47 | const headers = parseRow(lines[0]) |
| 48 | const rows = lines.slice(1).map(parseRow) |
| 49 | |
| 50 | return { headers, rows } |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Convert table data to CSV string |
no test coverage detected