-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv-parse.js
47 lines (41 loc) · 1.15 KB
/
csv-parse.js
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
export default (string, maxRows = Infinity) => {
let inQuote = false;
let field = '';
let row = [];
const result = [];
const charArray = [
// Chomp final line terminator
...string.replace(/(?:\r\n|\n|\r)$/u, '')
];
for (let index = 0; index < charArray.length; index++) {
const current = charArray[index];
const next = charArray[index + 1];
if (!inQuote && ',\r\n'.includes(current)) {
row.push(field);
field = '';
if (current !== ',') {
if (current + next === '\r\n') {
index++;
}
result.push(row);
if (result.length >= maxRows) {
return result;
}
row = [];
}
} else if (current !== '"') {
field += current;
} else if (!inQuote) {
inQuote = true;
} else if (next === '"') {
field += '"';
index++;
} else {
inQuote = false;
}
}
// Add the last field
row.push(field);
result.push(row);
return result;
};