Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

TypeScript · 99 lines · 2.7 KiB · at 8b87e58

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);  }}type Row = { line: number; fields: string[] } | { line: number; unterminated: true };const readRows = (text: string): Row[] => {  const rows: Row[] = [];  const n = text.length;  let i = 0;  let line = 1;  const atBreak = () => text[i] === "\n" || text.startsWith("\r\n", i);  const skipBreak = () => {    i += text[i] === "\n" ? 1 : 2;    line += 1;  };  while (i < n) {    if (atBreak()) {      skipBreak();      continue;    }    const startLine = line;    const fields: string[] = [];    for (;;) {      let value = "";      if (text[i] === '"') {        i += 1;        let closed = false;        while (i < n) {          const c = text[i];          if (c === '"') {            if (text[i + 1] === '"') {              value += '"';              i += 2;            } else {              i += 1;              closed = true;              break;            }          } else {            if (c === "\n") line += 1;            value += c;            i += 1;          }        }        if (!closed) {          rows.push({ line: startLine, unterminated: true });          return rows;        }      }      while (i < n && text[i] !== "," && !atBreak()) {        value += text[i];        i += 1;      }      fields.push(value);      if (i < n && text[i] === ",") {        i += 1;        continue;      }      if (i < n) skipBreak();      break;    }    rows.push({ line: startLine, fields });  }  return rows;};/** Throws CsvError. */export function parseCsv(text: string, requiredColumns: string[]): Record<string, string>[] {  const rows = readRows(text);  if (rows.length === 0) throw new CsvError("missing_header");  const head = rows[0];  if (!("fields" in head)) throw new CsvError("unterminated_quote", { line: head.line });  const header = head.fields;  for (const column of requiredColumns) {    if (!header.includes(column)) throw new CsvError("missing_column", { column });  }  const out: Record<string, string>[] = [];  for (const row of rows.slice(1)) {    if (!("fields" in row)) throw new CsvError("unterminated_quote", { line: row.line });    if (row.fields.length !== header.length) throw new CsvError("column_count", { line: row.line });    const record: Record<string, string> = {};    header.forEach((name, k) => {      record[name] = row.fields[k];    });    out.push(record);  }  return out;}