Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
377 lines (311 loc) · 12.5 KB
/
Copy pathapp.js
File metadata and controls
377 lines (311 loc) · 12.5 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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
// CSV Table Inspector - Main Application Logic
class CSVInspector {
constructor() {
this.data = [];
this.headers = [];
this.filteredData = [];
this.sortColumn = null;
this.sortDirection = 'asc';
this.initializeEventListeners();
}
initializeEventListeners() {
document.getElementById('fileInput').addEventListener('change', (e) => this.handleFileSelect(e));
document.getElementById('applyFilter').addEventListener('click', () => this.applyFilter());
document.getElementById('clearFilter').addEventListener('click', () => this.clearFilter());
document.getElementById('exportCSV').addEventListener('click', () => this.exportData('csv'));
document.getElementById('exportJSON').addEventListener('click', () => this.exportData('json'));
document.getElementById('showStats').addEventListener('click', () => this.showStatistics());
document.getElementById('closeStats').addEventListener('click', () => this.hideStatistics());
// Close modal when clicking outside
document.getElementById('statsModal').addEventListener('click', (e) => {
if (e.target.id === 'statsModal') {
this.hideStatistics();
}
});
// Filter on Enter key
document.getElementById('filterValue').addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
this.applyFilter();
}
});
}
handleFileSelect(event) {
const file = event.target.files[0];
if (!file) return;
document.getElementById('fileName').textContent = file.name;
const reader = new FileReader();
reader.onload = (e) => {
const content = e.target.result;
this.parseCSV(content);
};
reader.readAsText(file);
}
parseCSV(content) {
const lines = content.split('\n').filter(line => line.trim());
if (lines.length === 0) {
alert('The CSV file is empty');
return;
}
// Parse headers
this.headers = this.parseLine(lines[0]);
// Parse data rows
this.data = [];
for (let i = 1; i < lines.length; i++) {
const values = this.parseLine(lines[i]);
if (values.length === this.headers.length) {
const row = {};
this.headers.forEach((header, index) => {
row[header] = values[index];
});
this.data.push(row);
}
}
this.filteredData = [...this.data];
this.renderTable();
this.populateFilterColumn();
this.showControls();
}
parseLine(line) {
const result = [];
let current = '';
let inQuotes = false;
for (let i = 0; i < line.length; i++) {
const char = line[i];
const nextChar = line[i + 1];
if (char === '"') {
if (inQuotes && nextChar === '"') {
current += '"';
i++;
} else {
inQuotes = !inQuotes;
}
} else if (char === ',' && !inQuotes) {
result.push(current.trim());
current = '';
} else {
current += char;
}
}
result.push(current.trim());
return result;
}
renderTable() {
const tableHead = document.getElementById('tableHead');
const tableBody = document.getElementById('tableBody');
// Clear existing content
tableHead.innerHTML = '';
tableBody.innerHTML = '';
// Render headers
const headerRow = document.createElement('tr');
this.headers.forEach((header, index) => {
const th = document.createElement('th');
th.textContent = header;
th.classList.add('sortable');
// Add sort class if this column is sorted
if (this.sortColumn === index) {
th.classList.add(this.sortDirection === 'asc' ? 'sort-asc' : 'sort-desc');
}
th.addEventListener('click', () => this.sortTable(index));
headerRow.appendChild(th);
});
tableHead.appendChild(headerRow);
// Render data rows
this.filteredData.forEach(row => {
const tr = document.createElement('tr');
this.headers.forEach(header => {
const td = document.createElement('td');
td.textContent = row[header];
tr.appendChild(td);
});
tableBody.appendChild(tr);
});
// Update info
document.getElementById('rowCount').textContent = `${this.filteredData.length} rows`;
document.getElementById('columnCount').textContent = `${this.headers.length} columns`;
// Show table
document.getElementById('tableContainer').classList.remove('hidden');
}
sortTable(columnIndex) {
const header = this.headers[columnIndex];
// Toggle sort direction if clicking the same column
if (this.sortColumn === columnIndex) {
this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
} else {
this.sortColumn = columnIndex;
this.sortDirection = 'asc';
}
this.filteredData.sort((a, b) => {
const aValue = a[header];
const bValue = b[header];
// Try numeric comparison
const aNum = parseFloat(aValue);
const bNum = parseFloat(bValue);
if (!isNaN(aNum) && !isNaN(bNum)) {
return this.sortDirection === 'asc' ? aNum - bNum : bNum - aNum;
}
// String comparison
const comparison = aValue.localeCompare(bValue);
return this.sortDirection === 'asc' ? comparison : -comparison;
});
this.renderTable();
}
populateFilterColumn() {
const select = document.getElementById('filterColumn');
select.innerHTML = '<option value="">Select column...</option>';
this.headers.forEach(header => {
const option = document.createElement('option');
option.value = header;
option.textContent = header;
select.appendChild(option);
});
}
applyFilter() {
const column = document.getElementById('filterColumn').value;
const value = document.getElementById('filterValue').value.toLowerCase();
if (!column || !value) {
alert('Please select a column and enter a filter value');
return;
}
this.filteredData = this.data.filter(row => {
const cellValue = row[column];
return cellValue != null && String(cellValue).toLowerCase().includes(value);
});
this.renderTable();
}
clearFilter() {
this.filteredData = [...this.data];
document.getElementById('filterColumn').value = '';
document.getElementById('filterValue').value = '';
this.renderTable();
}
showControls() {
document.getElementById('controls').classList.remove('hidden');
}
exportData(format) {
if (this.filteredData.length === 0) {
alert('No data to export');
return;
}
let content, mimeType, extension;
if (format === 'csv') {
content = this.toCSV(this.filteredData);
mimeType = 'text/csv';
extension = 'csv';
} else if (format === 'json') {
content = JSON.stringify(this.filteredData, null, 2);
mimeType = 'application/json';
extension = 'json';
}
this.downloadFile(content, `export.${extension}`, mimeType);
}
toCSV(data) {
const headers = this.headers.map(h => this.escapeCSV(h)).join(',');
const rows = data.map(row => {
return this.headers.map(header => this.escapeCSV(row[header])).join(',');
});
return [headers, ...rows].join('\n');
}
escapeCSV(value) {
// Handle null, undefined, and non-string values
if (value == null) {
return '';
}
const strValue = String(value);
if (strValue.includes(',') || strValue.includes('"') || strValue.includes('\n')) {
return `"${strValue.replace(/"/g, '""')}"`;
}
return strValue;
}
downloadFile(content, filename, mimeType) {
const blob = new Blob([content], { type: mimeType });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
showStatistics() {
const statsContent = document.getElementById('statsContent');
statsContent.innerHTML = '';
this.headers.forEach(header => {
const columnData = this.filteredData.map(row => row[header]);
const stats = this.calculateStats(columnData, header);
const columnDiv = document.createElement('div');
columnDiv.className = 'stats-column';
const title = document.createElement('h3');
title.textContent = header;
columnDiv.appendChild(title);
const statsGrid = document.createElement('div');
statsGrid.className = 'stats-grid';
Object.entries(stats).forEach(([label, value]) => {
const statItem = document.createElement('div');
statItem.className = 'stat-item';
const statLabel = document.createElement('span');
statLabel.className = 'stat-label';
statLabel.textContent = label + ':';
const statValue = document.createElement('span');
statValue.className = 'stat-value';
statValue.textContent = value;
statItem.appendChild(statLabel);
statItem.appendChild(statValue);
statsGrid.appendChild(statItem);
});
columnDiv.appendChild(statsGrid);
statsContent.appendChild(columnDiv);
});
document.getElementById('statsModal').classList.remove('hidden');
}
hideStatistics() {
document.getElementById('statsModal').classList.add('hidden');
}
calculateStats(data, columnName) {
const stats = {
'Count': data.length,
'Unique': new Set(data).size,
'Empty': data.filter(v => {
// Treat null and undefined as empty
if (v == null) return true;
// For strings, check if empty after trimming
if (typeof v === 'string') return v.trim() === '';
// Numbers (including 0) and booleans are not considered empty
return false;
}).length
};
// Try to calculate numeric statistics
const numericData = data.map(v => parseFloat(v)).filter(v => !isNaN(v));
if (numericData.length > 0) {
stats['Numeric Count'] = numericData.length;
// Use loop-based approach for large arrays to avoid stack overflow
let min = numericData[0];
let max = numericData[0];
let sum = 0;
for (let i = 0; i < numericData.length; i++) {
const val = numericData[i];
if (val < min) min = val;
if (val > max) max = val;
sum += val;
}
stats['Min'] = min.toFixed(2);
stats['Max'] = max.toFixed(2);
stats['Average'] = (sum / numericData.length).toFixed(2);
stats['Sum'] = sum.toFixed(2);
}
// Find most common value
const frequency = {};
data.forEach(value => {
// Convert null/undefined to string representation for consistent counting
const key = value == null ? String(value) : value;
frequency[key] = (frequency[key] || 0) + 1;
});
const mostCommon = Object.entries(frequency).sort((a, b) => b[1] - a[1])[0];
if (mostCommon) {
stats['Most Common'] = `${mostCommon[0]} (${mostCommon[1]}x)`;
}
return stats;
}
}
// Initialize the application
const app = new CSVInspector();