Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Markdown · 1.4 KiB · at b0c0c21

Write parseCsv(text, requiredColumns), which parses CSV text into an array of records keyed by the header row.

Format:

  • Fields are separated by commas. Line breaks are \n or \r\n.
  • A field that starts with a double quote is quoted: it runs to the next unpaired ", may contain commas and line breaks (kept verbatim), and "" inside it stands for one ". A quote character inside an unquoted field is an ordinary character.
  • The first row is the header. Every later row becomes one record whose keys are the header fields and whose values are that row's fields, as strings.
  • A completely empty line (nothing between two line breaks, or between a line break and the end of the text) is skipped and is not a row. A trailing line break does not create a row.

Line numbers are 1-based physical lines of the text. Every line counts, including skipped blank lines and lines inside quoted fields. A row's line is the line on which it starts.

Errors, reported in this order:

  • { kind: "missing_header" } when the text has no rows at all (it is empty or contains only blank lines).
  • { kind: "missing_column", column } when a name in requiredColumns is not a header field; column is the first such name in requiredColumns order.
  • Then the first bad row, in order of appearance: { kind: "column_count", line } when a row has a different number of fields than the header, or { kind: "unterminated_quote", line } when a quoted field is never closed.