Skip to content

Instantly share code, notes, and snippets.

@PanJarda
Last active November 2, 2019 00:22
Show Gist options
  • Save PanJarda/4c68ca7da35ab247c26a5ef10848007f to your computer and use it in GitHub Desktop.
Save PanJarda/4c68ca7da35ab247c26a5ef10848007f to your computer and use it in GitHub Desktop.
CSV RFC 4180 parser
/*
* CSV parser
*
* See RFC 4180 for CSV format specification.
*
* License MIT
* JP2019
*/
/**
* "1,2,3\n4,5,6" -> [["1", "2", "3"], ["4", "5", "6"]]
* @param {string} csv - csv formatted string
* @param {Array} res - array for result
* @param {string} delimiter - optional, defaults to ','
* @return {number} error code
*/
function csv2arr(csv, res, delimiter) {
delimiter = delimiter || ',';
var ERR_MISSING_QUOTE = 1, /* no enclosing quote */
i = 0, /* current index */
j, /* cell start index */
c,
row = [],
col = '',
I,
N = csv.length;
if (csv.charCodeAt(N-1) === 10) N--;
if (csv.charCodeAt(N-1) === 13) N--;
col:
while (true) {
if (csv.charCodeAt(i) === 34) {
j = ++i;
i = csv.indexOf('"', j);
if (i < 0) {
//err = ERR_MISSING_QUOTE;
i = N;
}
col += csv.slice(j, i++);
while((c=csv.charCodeAt(i)) === 34) {
j = i++;
i = csv.indexOf('"', i);
if (i < 0) {
//err = ERR_MISSING_QUOTE;
i = N;
}
col += csv.slice(j, i++);
}
row.push(col);
col='';
switch(c) {
case 13:
if (csv.charCodeAt(i+1) === 10) ++i;
case 10:
res.push(row);
row = [];
}
i++;
continue;
}
j = i;
while(i < N) {
switch(csv.charCodeAt(I = i)) {
case 13:
if (csv.charCodeAt(i+1) === 10) ++i;
case 10:
row.push(csv.slice(j, I))
res.push(row);
row = [];
i++;
continue col;
case 44:
row.push(csv.slice(j, I));
i++;
continue col;
}
i++;
}
row.push(col || csv.slice(j, i));
res.push(row);
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment