-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.js
71 lines (66 loc) · 1.38 KB
/
utils.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
function parseCSV(str) {
var arr = [];
var quote = false;
let c, col;
for (let row = (col = c = 0); c < str.length; c++) {
var cc = str[c],
nc = str[c + 1];
arr[row] = arr[row] || [];
arr[row][col] = arr[row][col] || "";
if (cc == '"' && quote && nc == '"') {
arr[row][col] += cc;
++c;
continue;
}
if (cc == '"') {
quote = !quote;
continue;
}
if (cc == "," && !quote) {
++col;
continue;
}
if (cc == "\r" && nc == "\n" && !quote) {
++row;
col = 0;
++c;
continue;
}
if (cc == "\n" && !quote) {
++row;
col = 0;
continue;
}
if (cc == "\r" && !quote) {
++row;
col = 0;
continue;
}
arr[row][col] += cc;
}
return arr;
}
function parseCSVtoObjects(csvString, /* optional */ columnNames) {
var csvRows = parseCSV(csvString);
var firstDataRow = 0;
if (!columnNames) {
columnNames = csvRows[0];
firstDataRow = 1;
}
var result = [];
for (var i = firstDataRow, n = csvRows.length; i < n; i++) {
var rowObject = {};
var row = csvRows[i];
for (
var j = 0, m = Math.min(row.length, columnNames.length);
j < m;
j++
) {
var columnName = columnNames[j];
var columnValue = row[j];
rowObject[columnName] = columnValue;
}
result.push(rowObject);
}
return result;
}