Skip to content

Instantly share code, notes, and snippets.

@thomaswilburn
Created June 24, 2017 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomaswilburn/c3eab0ce5d8b0c9484f88e60a84fbf91 to your computer and use it in GitHub Desktop.
Save thomaswilburn/c3eab0ce5d8b0c9484f88e60a84fbf91 to your computer and use it in GitHub Desktop.
Minimal CSV module
var isNumber = /^-?\d[\d.,]*$/;
var cast = function(str) {
if (typeof str != "string") return str;
if (str == "true" || str == "false") {
return str == "true" ? true : false;
}
if (isNumber.test(str)) {
return parseFloat(str.replace(/,/g, ""));
}
return str;
};
var parseLine = function(line) {
var columns = [];
var buffer = "";
var quoted = false;
for (var i = 0; i < line.length; i++) {
var char = line[i];
switch (char) {
case `"`:
//handle escaped quotes
if (line[i+1] == `"` && line[i+2] == `"`) {
buffer += `"`;
i += 2;
} else {
quoted = !quoted;
}
break;
case ",":
if (!quoted) {
columns.push(buffer);
buffer = "";
break;
}
default:
buffer += char;
}
}
if (buffer) {
columns.push(buffer);
}
return columns;
}
module.exports = function(text, noHeader) {
var lines = text.replace(/\r/g, "").split("\n");
var header = parseLine(lines.shift());
lines = lines.map(function(l) {
var values = parseLine(l).map(cast);
var named = {};
values.forEach(function(v, index) {
var key = header[index] || index;
named[key] = v;
})
return named;
});
return lines;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment