I recently published a JavaScript module for NPM which is also available on Github by the name of rawiki-parse-csv. The code takes raw CSV data and returns an array. The method has one option to include the first line as a header in which case an object is returned within the array. If the option is not set each line will be returned as an array.
The project includes a Chai test which inputs some sample CSV data and checks the returned output with both options specified. The tests pass without issue and use in an actual application appears to be faultless.
Could someone comment on any issues with this code, potentials for failure, incorrect structure or areas for improvement?
/*
The MIT License (MIT)
Copyright (c) 2016 Rawikitua Isherwood
Parse module creates an object or set of arrays from a csv file by splitting the text at each new
line and splitting each line at comma marks.*/
var parse = function (input, option){
try
{
// output object
var data = {},
// output no columns array
container = [],
// output array
records = [],
// splits csv data at each new line
lines =input.split(/\r\n|\r|\n/),
// creates columns by splitting first line of csv
columns = lines[0].split(',');
// creates objects from csv data if column option included
if (option === true){
// loop through each line of csv file
for (var l = 1; l <= lines.length-1; l++)
{
// splits each line of csv by comma
var words = lines[l].split(',');
// builds object based on column headers
for (var cell in columns)
{
data[columns[cell]] = words[cell];
}
// pushes object to output array
records.push(data);
// resets object in order to add another
data = {};
}
}
else {
// creates nested arrays from csv data if column option omitted,false or not true
for (var l = 0; l <= lines.length-1; l++)
{
// splits each line of csv by comma
var words = lines[l].split(',');
// creates objects from csv data
for (var cell in words)
{
container.push(words[cell]);
}
// push array to output array
records.push(container);
// reset array in order to add another
container = [];
}
}
// returns output array
return records
}
catch(err){
return err
}
}
module.exports = parse
l <= lines.length - 1
was used because the length property counts from 1 and arrays start at zero and I would otherwise need to minus one froml
when it's used as a key in my arrays. As for writing this using two separate functions I had thought this would create more duplicate code so I tried to duplicate only that which was necessary to achieve the desired functionality. Would splitting this into multiple functions still be best practice? Otherwise I'm going to do a complete rewrite when I can to implement the rest of the points you've given. \$\endgroup\$