-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathcsv-parser.js
61 lines (54 loc) · 1.58 KB
/
csv-parser.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
/**
* We're going to implement a simple CSV parsing function.
* There are two things to focus on. The first (and most importantly)
* is correctly parsing the CSV format. The second is writing
* clean code that another engineer would enjoy using.
*
* You may assume that the CSV file is correctly formatted.
*
* csv_lines = [
* 'John,Smith,[email protected],Los Angeles,10',
* 'Jane,Roberts,[email protected],"San Francisco, CA",0',
* '"Alexandra ""Alex""",Menendez,[email protected],Miami,1',
* '1,2,,4,"5"'
* ]
*
* An ideal parse will look like this:
* [['John', 'Smith', '[email protected]', 'Los Angeles', '1'],
* ['Jane', 'Roberts', '[email protected]', 'San Francisco, CA', '0'],
* ['Alexandra "Alex"', 'Menendez', '[email protected]', 'Miami', '1'],
* ['1','2','','4','5']]
*/
/**
* Parse one line of CSV
* @param {string} text
* @return {string[]}
*/
const parseCSVLine = text => {
const arr = [''];
let i = 0; // current index
let p = ''; // previous character
let s = true; // whether we have seen a pair of double quotes
for (let c of text) {
if (c === '"') {
s = !s;
if (p === '"') {
arr[i] += '"'; // the previous character is also double quote
c = ''; // reset previous character
}
} else if (s && c === ',') {
c = arr[++i] = ''; // reset previous character
} else {
arr[i] += c;
}
p = c;
}
return arr;
};
/**
* Parse CSV
* @param {string[]} csvLines
* @return {string[][]}
*/
const parseCSV = csvLines => csvLines.map(line => parseCSVLine(line));
export { parseCSV };