-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
54 lines (39 loc) 路 1.65 KB
/
Copy pathscript.js
File metadata and controls
54 lines (39 loc) 路 1.65 KB
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
const tableContainer = document.querySelector('.table-container');
const fieldFile = document.querySelector('.field-file');
const getColumns = (column, content) => column += `<td>${content}</td>`;
const getRows = (rows, data) => {
const row = data.replace(/,\s|,|\|/g, ', ').split(', ');
const columns = row.reduce(getColumns, '');
return rows += `<tr>${columns}</tr>`;
}
const defineTableBodyContent = (tbody, datas) =>
tbody.innerHTML = datas.reduce(getRows, '');
const defineTableHeadings = (thead, datas) =>
thead.innerHTML = datas.replace(/,\s|,|\|/g, ', ')
.split(', ')
.reduce((acc, data) => acc += `<th>${data}</th>`, '');
const addTableIntoDOM = (dataString) => {
tableContainer.innerHTML = '';
const table = document.createElement('table');
const thead = table.createTHead();
const tbody = table.createTBody();
const datasWithoutLineBreak = dataString.split('\n')
.filter((data) => data !== '');
defineTableHeadings(thead, datasWithoutLineBreak[0]);
defineTableBodyContent(tbody, datasWithoutLineBreak.splice(1));
tableContainer.appendChild(table);
}
const readFileUploaded = () => {
const reader = new FileReader();
const file = fieldFile.files[0];
reader.onload = ({ target: { result } }) => addTableIntoDOM(result);
reader.readAsText(file);
}
const upload = () => {
const regexToCsvAndTxt = /([a-zA-Z0-9\s.\\:_-])+(.csv|.txt)/g;
const filenameToTest = fieldFile.value.toLowerCase();
const isCsvOrTxtAndFileReaderExists = regexToCsvAndTxt.test(filenameToTest)
&& typeof (FileReader) !== 'undefined';
if (isCsvOrTxtAndFileReaderExists) readFileUploaded();
}
fieldFile.addEventListener('change', upload);