Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

TypeScript · 52 lines · 1.9 KiB · at f30ac63

// Bug: reports the row's position among non-blank records instead of its physical line (ignores skipped blank lines and newlines inside quotes).export type CsvErrorKind = "missing_header" | "missing_column" | "column_count" | "unterminated_quote";export class CsvError extends Error {  readonly column?: string;  readonly line?: number;  constructor(    public readonly kind: CsvErrorKind,    detail: { column?: string; line?: number } = {},  ) {    super(kind);    Object.assign(this, detail);  }}export function parseCsv(text: string, requiredColumns: string[]): Record<string, string>[] {  const rows: string[][] = [];  let field = "";  let row: string[] = [];  let inQuotes = false;  let i = 0;  while (i < text.length) {    const c = text[i];    if (inQuotes) {      if (c === '"' && text[i + 1] === '"') { field += '"'; i += 2; continue; }      if (c === '"') { inQuotes = false; i++; continue; }      field += c; i++; continue;    }    if (c === '"' && field === "") { inQuotes = true; i++; continue; }    if (c === ",") { row.push(field); field = ""; i++; continue; }    if (c === "\r" && text[i + 1] === "\n") { i++; continue; }    if (c === "\n") {      row.push(field);      if (!(row.length === 1 && row[0] === "")) rows.push(row);      row = []; field = ""; i++; continue;    }    field += c; i++;  }  if (inQuotes) throw new CsvError("unterminated_quote", { line: rows.length + 1 });  if (field !== "" || row.length > 0) { row.push(field); rows.push(row); }  if (rows.length === 0) throw new CsvError("missing_header");  const header = rows[0];  for (const column of requiredColumns) {    if (!header.includes(column)) throw new CsvError("missing_column", { column });  }  return rows.slice(1).map((r, k) => {    if (r.length !== header.length) throw new CsvError("column_count", { line: k + 2 });    const rec: Record<string, string> = {};    header.forEach((name, j) => (rec[name] = r[j]));    return rec;  });}