-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathCsvToTable.js
104 lines (93 loc) · 2.67 KB
/
CsvToTable.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
(function(){
// Constructor method
this.CsvToTable = function(){
this.csvFile = null;
// Create options by extending defaults with the passed in arugments
if (arguments[0] && typeof arguments[0] === "object") {
this.options = arguments[0];
}
}
CsvToTable.prototype.run = function() {
return buildTable.call(this);
}
function getCSV() {
try{
var csvfile = this.options.csvFile;
return new Promise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.open("GET", csvfile, true);
request.onload = function() {
if (request.status == 200) {
resolve(request.response);
} else {
reject(Error(request.statusText));
}
};
request.onerror = function() {
reject(Error('Error fetching data.'));
};
request.send();
});
}catch(err){
console.error(err);
}
}
function isNotEmpty(row) {
return row !== "";
}
// polyfill `.filter()` for ECMAScript <5.1
// `f` must be pure (not modify original array).
if (!Array.prototype.filter) {
Array.prototype.filter = function(f) {
"use strict";
var p = arguments[1];
var o = Object(this);
var len = o.length;
for (var i = 0; i < len; i++) {
if (i in o) {
var v = o[i];
f.call(p, v, i, o);
}
}
return this;
};
}
function buildTable() {
getCSV.call(this).then(function(response){
var allRows = response.split(/\r?\n|\r/).filter(isNotEmpty);
var table = '<table>';
for (var singleRow = 0; singleRow < allRows.length; singleRow++) {
if (singleRow === 0) {
table += '<thead>';
table += '<tr>';
} else {
table += '<tr>';
}
var rowCells = allRows[singleRow].split(',');
for(var rowCell = 0; rowCell < rowCells.length; rowCell++){
if(singleRow === 0){
table += '<th>';
table += rowCells[rowCell];
table += '</th>';
} else {
table += '<td>';
table += rowCells[rowCell];
table += '</td>';
}
}
if (singleRow === 0) {
table += '</tr>';
table += '</thead>';
table += '<tbody>';
} else {
table += '</tr>';
}
}
table += '</tbody>';
table += '</table>';
document.body.innerHTML += table;
}, function(error){
console.error(error);
});
}
}());