-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparseCSV.js
68 lines (60 loc) · 1.78 KB
/
parseCSV.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
/**
* Parses a CSV string that represents an array of columns.
* @param {string} csvRowString - The CSV data as a string.
* @returns {string[]} - An array of columns.
*/
export function parseCSVRow(csvRowString) {
let currentColumn = '';
let inQuotes = false;
const columns = [];
const row = csvRowString.split('');
for (let i = 0; i < row.length; i++) {
const char = row[i];
if (char === '"') {
inQuotes = !inQuotes;
} else if (char === ',' && !inQuotes) {
columns.push(currentColumn.trim());
currentColumn = '';
} else {
currentColumn += char;
}
}
columns.push(currentColumn.trim());
return columns;
}
/**
* Parses a CSV string and returns a 2D array of rows and columns.
* @param {string} csvString - The CSV data as a string.
* @returns {string[][]} - A 2D array of rows and columns.
*/
export function parseCSV(csvString) {
const rows = csvString.trim().split('\n');
const maxColumns = 0;
const data = rows.map(parseCSVRow);
const maxColumnCount = Math.max(...data.map((row) => row.length));
return data.map((row) => {
while (row.length < maxColumnCount) {
row.push('');
}
return row;
});
}
/**
* stringifyCSVRow takes an array of strings and returns a CSV encoded string.
*/
export function stringifyCSVRow(array) {
return array.map(field => {
// Check if the field contains a comma, newline, or double quote
if (/[",\n]/.test(field)) {
// Escape double quotes and enclose the field in double quotes
return `"${field.replace(/"/g, '""')}"`;
}
return field;
}).join(',');
}
/**
* stringifyCSV a 2D array of strings (rows and columns) and returns a CSV encoded string.
*/
export function stringifyCSV(data) {
return data.map(stringifyCSVRow).join('\n');
}