Parse CSV with Quoted Fields

Write the code, see it run, pass the checks.

The problem

  • hard
  • Code
  • Pro

Write parseCsv(text), which returns the rows of a CSV file as an array of arrays of strings. Fields are separated by commas and rows by line breaks: a line feed (character code 10), a carriage return followed by a line feed (codes 13 and 10), or a carriage return on its own. The checks build these with String.fromCharCode. A field that starts with a double quote is quoted: it runs to the closing quote, any commas and line breaks inside it belong to the field, and two double quotes in a row inside it stand for one. The quotes around it aren't part of the value. Other fields are taken exactly as written, spaces included. Empty fields are kept, so "a,,c" has three fields and a line ending in a comma ends with an empty field, and an empty line in the middle is a row with one empty field. A line break at the very end doesn't add a row, and empty text gives no rows. Throw an Error if a quoted field is never closed.

Your code must pass

  • Splits rows and fields
  • Keeps empty fields and empty lines
  • Reads commas inside quoted fields
  • Turns two double quotes into one
  • Keeps line breaks inside quoted fields
  • Accepts Windows line endings and a final line break
  • Throws when a quote is never closed