-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsv.min.js
1 lines (1 loc) · 2.74 KB
/
csv.min.js
1
class csvJS{constructor(t=",",e="\n"){return this.COMMA=",",this.SEMI_COMMA=";",this.COLON=":",this.BAR="|",this.TAB="\t",this.NL="\n",this.JSON_OPTION_REGULAR=1,this.JSON_OPTION_TRANSPOSE=2,this.setSplice=void 0!==t?t:this.COMMA,this.setEOF=void 0!==e?e:this.NL,this.results,this}fromFile(t,e=0){const s=this.setSplice,r=this.setEOF,i=[],n=[],l=new XMLHttpRequest;if(!t.match(/\.csv$/))throw new TypeError("Your file must be a CSV file");return l.onreadystatechange=function(){if(4===this.readyState&&200==this.status){let t=this.responseText;t=t.replaceAll("\r","").trim();const l=t.split(r);for(let t=0;t<l.length;t++)if(0==t)l[t].split(s).forEach((t=>{n.push(t.trim())}));else if(!Array.isArray(e)&&t!=e||Array.isArray(e)&&!e.includes(t)){const e=new Object;for(let r=0;r<n.length;r++){l[t]=l[t].replace(new RegExp(s+"$"),"");const i=l[t].split(s);e[n[r]]=i[r].trim()}i.push(e)}}},l.open("GET",t,!1),l.send(),this.results=i,this}fromString(t,e=0){let s=t;const r=this.setSplice,i=this.setEOF,n=[],l=[];s=s.replaceAll("\r","").trim();const c=s.split(i);for(let t=0;t<c.length;t++)if(0==t)c[t].split(r).forEach((t=>{l.push(t.trim())}));else if(!Array.isArray(e)&&t!=e||Array.isArray(e)&&!e.includes(t)){const e=new Object;for(let s=0;s<l.length;s++){c[t]=c[t].replace(new RegExp(r+"$"),"");const i=c[t].split(r);e[l[s]]=i[s].trim()}n.push(e)}return this.results=n,this}toTable(t){obj=this.results;const e=document.createElement("table"),s=document.createElement("thead"),r=document.createElement("tbody"),i=document.createElement("tr"),n=Object.keys(obj[0]);if("object"!=typeof obj)throw new TypeError("Argument must be an object");n.forEach((t=>{const e=document.createElement("th");e.innerText=t,i.appendChild(e)})),s.appendChild(i),e.appendChild(s);for(let t=0;t<obj.length;t++){const e=Object.values(obj[t]),s=document.createElement("tr");for(let t=0;t<e.length;t++){const r=document.createElement("td");r.innerText=e[t],s.appendChild(r)}r.appendChild(s)}e.appendChild(r),document.querySelector(t).appendChild(e)}toCSV(){const t=this.results;let e="",s=Object.keys(t[0]);return e+=s.join(this.setSplice)+this.setEOF,t.forEach((t=>{const s=Object.values(t);e+=s.join(this.setSplice).trim()+this.setEOF})),e=e.replace(new RegExp(this.setEOF+"$"),""),e}#t(t){let e={};for(let s=0;s<1;s++)Object.keys(t[s]).forEach((t=>{e[t]=[]}));for(let s=0;s<t.length;s++)Object.keys(t[s]).forEach((r=>{e[r].push(t[s][r])}));return e}toSQL(){const t=this.results;let e=`INSERT INTO (${Object.keys(t[0]).join(",")}) VALUES `;for(let s=0;s<t.length;s++){e+=`(${Object.values(t[s]).join(",")}), `}return e=e.replace(/, ?$/,""),e}toJSON(t){const e=this.results;let s;switch(t){case this.JSON_OPTION_REGULAR:s=JSON.stringify(e);break;case this.JSON_OPTION_TRANSPOSE:s=this.#t(e);break;default:s=JSON.stringify(e)}return s}}