Updated to be more efficient

This commit is contained in:
2020-12-24 07:19:09 +11:00
parent 0a007862e7
commit 992e025e6b
2 changed files with 40 additions and 29 deletions

View File

@ -6,8 +6,9 @@ efficient and no dependencies.
Only one method is provided; Only one method is provided;
```js ```js
const csv = 'Name,Age,Location\nDom,26,Sydney\nSteve,30,New York'; const csv = 'Name,Age,Location\nDom,26,Sydney\nSteve,30,New York';
parseCSV(csv, function(line) { parseCSV(csv, function(headers, line, index) {
console.log(line.name);//Dom then Steve console.log(index, '-', line[headers.indexOf('Name')]);//1 - Dom
return true;//Return false to break loop
}) })
``` ```
To stay efficient we ask for a callback that is fired for every line parsed. To stay efficient we ask for a callback that is fired for every line parsed.

View File

@ -1,43 +1,53 @@
function parseCSV(csv, onLine) { function parseCSV(csv, onLine) {
const lines = csv.split(/\r?\n/); //Split lines by delim, don't worry about \r here
const lines = csv.split('\n');
let headers = null; let headers = null;
let index = 0;
//For each line...
for(let i = 0; i < lines.length; i++) { for(let i = 0; i < lines.length; i++) {
//Shave off trailing whitespaces
let line = lines[i].trim(); let line = lines[i].trim();
if(!line.length) continue; if(!line.replace(/\s/g, '').length) continue;//Skip blank lines
index++;//Count real lines
let lineArray = []; //Setup line array
let currentValue = ''; let lineArray;
let encapsulated = false; if(line.indexOf('"') !== -1) {//Only escape lines with strings
let currentValue = '';//Store current value
let encapsulated = false;//Track when we're inside a "
lineArray = [];
for(let j = 0; j < line.length; j++) { //Foreach char in the line...
let c = line[j]; for(let j = 0; j < line.length; j++) {
let c = line[j];
if(!encapsulated && c == ',') { if(!encapsulated && c == ',') {
//Comma, make new cell //Comma, make new cell
lineArray.push(currentValue); lineArray.push(currentValue);
currentValue = ''; currentValue = '';
continue; continue;
} else if(c == '"') { } else if(c == '"') {
//Quote, begin string encapsulation //Quote, begin string encapsulation
encapsulated = !encapsulated; encapsulated = !encapsulated;
continue; continue;
}
currentValue += `${c}`;
} }
currentValue += `${c}`;
}
lineArray.push(currentValue);
//Is this the headers? //Add current value
lineArray.push(currentValue);
} else {
lineArray = line.split(',');
}
//Is this the headers line?
if(!headers) { if(!headers) {
headers = lineArray; headers = lineArray;
continue; continue;
} }
//This is a line //Callback
let x = {}; let r = onLine(headers, lineArray, index);
for(let j = 0; j < headers.length; j++) { if(!r) break;//If r != true then break loop
x[headers[j]] = lineArray[j] || '';
}
onLine(x);
} }
} }