-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv-parser.js
More file actions
84 lines (71 loc) · 2.29 KB
/
Copy pathcsv-parser.js
File metadata and controls
84 lines (71 loc) · 2.29 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Simple CSV parser for browser use
class CSVParser {
static parse(csvText) {
const lines = csvText.split('\n').filter(line => line.trim() !== '');
const headers = this.parseLine(lines[0]);
const data = [];
for (let i = 1; i < lines.length; i++) {
const values = this.parseLine(lines[i]);
if (values.length === headers.length) {
const row = {};
headers.forEach((header, index) => {
row[header] = values[index] || '';
});
data.push(row);
}
}
return data;
}
static parseLine(line) {
const result = [];
let current = '';
let inQuotes = false;
let i = 0;
while (i < line.length) {
const char = line[i];
const nextChar = line[i + 1];
if (char === '"') {
if (inQuotes && nextChar === '"') {
// Escaped quote
current += '"';
i += 2;
} else {
// Toggle quote state
inQuotes = !inQuotes;
i++;
}
} else if (char === ',' && !inQuotes) {
// Field separator
result.push(current.trim());
current = '';
i++;
} else {
current += char;
i++;
}
}
// Add the last field
result.push(current.trim());
return result;
}
static stringify(data) {
if (!data || data.length === 0) return '';
const headers = Object.keys(data[0]);
const csvLines = [];
// Add header row
csvLines.push(headers.map(header => this.escapeField(header)).join(','));
// Add data rows
data.forEach(row => {
const values = headers.map(header => this.escapeField(row[header] || ''));
csvLines.push(values.join(','));
});
return csvLines.join('\n');
}
static escapeField(field) {
const str = String(field);
if (str.includes(',') || str.includes('"') || str.includes('\n')) {
return '"' + str.replace(/"/g, '""') + '"';
}
return str;
}
}