-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv-parser.js
More file actions
115 lines (97 loc) · 3.14 KB
/
Copy pathcsv-parser.js
File metadata and controls
115 lines (97 loc) · 3.14 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/**
* CSV Parser Module
* Handles loading and parsing CSV files with support for quoted values,
* commas inside quotes, blank fields, and UTF-8 encoding.
*/
const CSVParser = (() => {
'use strict';
function parse(csvText) {
const rows = [];
const len = csvText.length;
let i = 0;
while (i < len) {
const { row, nextIndex } = parseRow(csvText, i, len);
if (row !== null) {
rows.push(row);
}
i = nextIndex;
}
if (rows.length === 0) return { headers: [], data: [] };
const headers = rows[0];
const data = [];
for (let r = 1; r < rows.length; r++) {
const obj = {};
for (let c = 0; c < headers.length; c++) {
obj[headers[c].trim()] = (rows[r][c] || '').trim();
}
data.push(obj);
}
return { headers: headers.map(h => h.trim()), data };
}
function parseRow(text, start, len) {
const fields = [];
let i = start;
if (i >= len) return { row: null, nextIndex: len };
while (i < len) {
if (text[i] === '"') {
const result = parseQuotedField(text, i, len);
fields.push(result.value);
i = result.nextIndex;
} else {
const result = parseUnquotedField(text, i, len);
fields.push(result.value);
i = result.nextIndex;
}
if (i < len && text[i] === ',') {
i++;
if (i >= len) {
fields.push('');
}
} else {
if (i < len && text[i] === '\r') i++;
if (i < len && text[i] === '\n') i++;
break;
}
}
if (fields.length === 1 && fields[0] === '' && start < len &&
(text[start] === '\n' || text[start] === '\r')) {
return { row: null, nextIndex: i };
}
return { row: fields, nextIndex: i };
}
function parseQuotedField(text, start, len) {
let value = '';
let i = start + 1;
while (i < len) {
if (text[i] === '"') {
if (i + 1 < len && text[i + 1] === '"') {
value += '"';
i += 2;
} else {
i++;
break;
}
} else {
value += text[i];
i++;
}
}
return { value, nextIndex: i };
}
function parseUnquotedField(text, start, len) {
let end = start;
while (end < len && text[end] !== ',' && text[end] !== '\n' && text[end] !== '\r') {
end++;
}
return { value: text.substring(start, end), nextIndex: end };
}
async function loadCSV(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to load CSV: ${response.status} ${response.statusText}`);
}
const text = await response.text();
return parse(text);
}
return { parse, loadCSV };
})();