17 lines
572 B
TypeScript
17 lines
572 B
TypeScript
|
|
function esc(v: unknown): string {
|
||
|
|
if (v === null || v === undefined) return "";
|
||
|
|
const s = String(v);
|
||
|
|
if (s.includes('"') || s.includes(",") || s.includes("\n") || s.includes(";")) {
|
||
|
|
return `"${s.replace(/"/g, '""')}"`;
|
||
|
|
}
|
||
|
|
return s;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function toCsv(rows: Record<string, unknown>[], columns?: string[]): string {
|
||
|
|
if (rows.length === 0) return "";
|
||
|
|
const cols = columns ?? Object.keys(rows[0]);
|
||
|
|
const head = cols.map(esc).join(",");
|
||
|
|
const body = rows.map((r) => cols.map((c) => esc(r[c])).join(",")).join("\n");
|
||
|
|
return `${head}\n${body}\n`;
|
||
|
|
}
|