Skip to content

Instantly share code, notes, and snippets.

@Pamblam
Created November 21, 2019 19:20
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 Pamblam/20160b775152dad2371a470b256377fd to your computer and use it in GitHub Desktop.
Save Pamblam/20160b775152dad2371a470b256377fd to your computer and use it in GitHub Desktop.
Parse csv strings per RFC 4180
class CSV{
constructor(data, has_header){
this.has_header = has_header;
this.headers = [];
this.rows = [];
this.headers = [];
this.raw = data;
this._iterator = 0;
this._in_quote = false;
this._char = false;
this.current_col = [];
this.current_row = [];
}
getNextChar(){
if(this._iterator >= this.raw.length) return false;
this._char = this.raw.charAt(this._iterator);
this._iterator++;
return true;
}
checkQuote(){
if(this._char !== '"') return;
this._in_quote = !this._in_quote;
}
parseColumn(){
var val = this.current_col.join('').trim();
if(val.charAt(0)==='"' && val.charAt(val.length-1) === '"'){
val = val.substring(1, val.length-2).replace(/""/g, '');
}
this.current_row.push(val);
this.current_col = []
}
checkComma(){
if(this._char === ',' && !this._in_quote){
this.parseColumn();
return false;
}
}
checkLnBr(){
if(this._char === "\n" && !this._in_quote){
this.parseColumn();
this.rows.push(this.current_row);
this.current_row = [];
return false;
}
}
parse(){
while(this.getNextChar()){
if(false === this.checkQuote()) continue;
if(false === this.checkComma()) continue;
if(false === this.checkLnBr()) continue;
this.current_col.push(this._char);
}
if(this.has_header) this.headers = this.rows.shift();
this.formatData();
return this.rows;
}
formatData(){
if(!this.has_header) return;
var ret = [];
for(var i=0; i<this.rows.length; i++){
var row = {};
for(var n=0; n<this.rows[i].length; n++){
var header = this.headers[n] || n;
row[header] = this.rows[i][n];
}
ret.push(row);
}
this.rows = ret;
}
}
(async ()=>{
const raw = await fetch('logs.csv').then(r=>r.text());
const csv = new CSV(raw, true);
var data = csv.parse();
console.log(data);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment