Spaces:
Sleeping
Sleeping
| /** Parse a CSV string into { headers, rows } */ | |
| export function parseCSV(text) { | |
| const lines = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n').filter(l => l.trim()); | |
| if (!lines.length) return { headers: [], rows: [] }; | |
| function splitLine(l) { | |
| const r = []; let c = '', q = false; | |
| for (let i = 0; i < l.length; i++) { | |
| const ch = l[i]; | |
| if (ch === '"') { q = !q; } | |
| else if (ch === ',' && !q) { r.push(c.trim()); c = ''; } | |
| else { c += ch; } | |
| } | |
| r.push(c.trim()); | |
| return r; | |
| } | |
| const headers = splitLine(lines[0]).map(h => h.replace(/^"|"$/g, '').trim()); | |
| const rows = lines.slice(1).map((ln, i) => { | |
| const vals = splitLine(ln); | |
| const o = { __id: i + 1 }; | |
| headers.forEach((h, j) => { o[h] = (vals[j] || '').replace(/^"|"$/g, '').trim(); }); | |
| return o; | |
| }); | |
| return { headers, rows }; | |
| } | |
| /** Parse with progress callback — calls cb(pct 0-100) periodically, then cb(100, result) */ | |
| export function parseCSVWithProgress(text, onProgress) { | |
| return new Promise(resolve => { | |
| const lines = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n').filter(l => l.trim()); | |
| const total = lines.length - 1; | |
| function splitLine(l) { | |
| const r = []; let c = '', q = false; | |
| for (let i = 0; i < l.length; i++) { | |
| const ch = l[i]; | |
| if (ch === '"') { q = !q; } | |
| else if (ch === ',' && !q) { r.push(c.trim()); c = ''; } | |
| else { c += ch; } | |
| } | |
| r.push(c.trim()); | |
| return r; | |
| } | |
| if (total <= 500) { | |
| const result = parseCSV(text); | |
| onProgress && onProgress(100, result); | |
| resolve(result); | |
| return; | |
| } | |
| const headers = splitLine(lines[0]).map(h => h.replace(/^"|"$/g, '').trim()); | |
| const rows = []; | |
| const CHUNK = 250; | |
| let i = 1; | |
| function step() { | |
| const end = Math.min(i + CHUNK, lines.length); | |
| for (; i < end; i++) { | |
| const vals = splitLine(lines[i]); | |
| const o = { __id: rows.length + 1 }; | |
| headers.forEach((h, j) => { o[h] = (vals[j] || '').replace(/^"|"$/g, '').trim(); }); | |
| rows.push(o); | |
| } | |
| const pct = Math.round((i - 1) / total * 100); | |
| onProgress && onProgress(pct, null); | |
| if (i < lines.length) { | |
| requestAnimationFrame(step); | |
| } else { | |
| const result = { headers, rows }; | |
| onProgress && onProgress(100, result); | |
| resolve(result); | |
| } | |
| } | |
| requestAnimationFrame(step); | |
| }); | |
| } | |
| export function fmtSize(bytes) { | |
| if (bytes < 1024) return bytes + ' B'; | |
| if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB'; | |
| return (bytes / 1048576).toFixed(2) + ' MB'; | |
| } | |
| export function pKey(row) { | |
| return String(row.__id !== undefined ? row.__id : row.key); | |
| } | |