← All Exercises

Typed CSV Parser with Quoted Fields

intermediatetypescript~15min

Background

CSV looks simple until values contain commas, quotes, or newlines. A small character-level parser plus typed column converters keeps imports predictable and catches bad numbers early.

Problem

Implement parseCsv<T>(text, schema) where schema maps each column to a converter returning the column's type. Parse the header, locate required columns, handle quoted fields with commas and doubled quotes, skip empty trailing records, and support CRLF input. Return rows typed as T.

Input

A JSON object with csv text whose first line is a header; the solution uses a fixed schema of id (number), name, and role.

Output

A JSON array of row objects with id as a number and the remaining columns as strings.

Sample tests

Sample 1

Input: {"csv":"id,name,role\n1,Ada,\"admin, dev\"\n2,Bob,\"say \"\"hi\"\"\"\n"}
Expected: [{"id":1,"name":"Ada","role":"admin, dev"},{"id":2,"name":"Bob","role":"say \"hi\""}]

Sample 2

Input: {"csv":"id,name,role\r\n1,Ada,dev\r\n"}
Expected: [{"id":1,"name":"Ada","role":"dev"}]

Your solution

Learning objective

Implement a small state-machine parser and connect it to typed column converters.