Lesson 153 of 296
Build: parse and transform data
On this page
What the task usually looks like
"Here is a CSV (or JSON) file of orders. Produce a report: total spent per customer, the top 3 customers, and a list of rows that are invalid." You have 45 to 60 minutes.
This tests: reading and validating messy data, choosing data structures (Map), grouping and sorting, money handling, and clean code structure.
Questions to ask first
- What is the exact format? Is there a header row? Which separator? Can fields contain commas inside quotes?
- What should happen to invalid rows: skip, stop, or report them?
- How are amounts written: pounds with decimals or pence? Which currency?
- How should ties in the top list be ordered?
- How big is the file? (Can it fit in memory? Part 15 covers streaming large files.)
The example input
orderId,customer,amount,date
1001,alice@example.com,19.99,2026-11-01
1002,bob@example.com,5.00,2026-11-02
1003,alice@example.com,"1,200.50",2026-11-03
1004,,12.00,2026-11-03
1005,carol@example.com,abc,2026-11-04
1006,Bob@Example.com,7.50,2026-11-05Problems hidden in it: an amount with a comma inside quotes, a missing customer, an amount that is not a number, and the same customer in different capitals.
Plan
- Parse each line into fields (handling quotes).
- Validate and convert each row into a typed
Order, or record an error with the line number. - Aggregate: total pence per customer in a Map.
- Report: sort and take the top N.
Each step is a separate small function, so each can be tested alone.
Step 1: parse a CSV line
function parseCsvLine(line: string): string[] {
const fields: string[] = [];
let current = "";
let inQuotes = false;
for (let i = 0; i < line.length; i++) {
const ch = line[i]!;
if (inQuotes) {
if (ch === '"' && line[i + 1] === '"') {
current += '"';
i++;
} else if (ch === '"') {
inQuotes = false;
} else {
current += ch;
}
} else if (ch === '"') {
inQuotes = true;
} else if (ch === ",") {
fields.push(current);
current = "";
} else {
current += ch;
}
}
fields.push(current);
return fields;
}- Commas inside quotes are part of the field.
- Two double quotes inside a quoted field mean one real quote (
""→"), as the CSV standard says. - In real projects use a tested library (such as
csv-parseorpapaparse). In an interview, say so, then write this simple version if they want to see it.
Step 2: validate and convert
type Order = {
orderId: string;
customer: string;
amountPence: number;
date: string;
};
type RowError = { line: number; reason: string };
function poundsToPence(text: string): number | null {
const cleaned = text.replace(/,/g, "").trim();
if (!/^\d+(\.\d{1,2})?$/.test(cleaned)) return null;
const [pounds, pennies = ""] = cleaned.split(".");
return Number(pounds) * 100 + Number(pennies.padEnd(2, "0"));
}
function toOrder(fields: string[], line: number): Order | RowError {
if (fields.length !== 4) {
return { line, reason: `expected 4 fields, got ${fields.length}` };
}
const [orderId, rawCustomer, rawAmount, date] = fields.map((f) => f.trim()) as [
string,
string,
string,
string
];
const customer = rawCustomer.toLowerCase();
if (!customer.includes("@")) return { line, reason: "missing or invalid customer" };
const amountPence = poundsToPence(rawAmount);
if (amountPence === null) return { line, reason: `invalid amount "${rawAmount}"` };
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return { line, reason: `invalid date "${date}"` };
return { orderId, customer, amountPence, date };
}- Money in pence (Lesson 49). Converting with string splitting avoids decimal errors (
19.99 * 100is1998.9999999999998). - Normalise the customer email to lower case, so "Bob@Example.com" and "bob@example.com" are one customer.
- Errors are returned, not thrown, so one bad row does not stop the whole report. The return type is a union; we tell the two apart below.
Step 3 and 4: aggregate and report
type Report = {
totals: { customer: string; totalPence: number }[];
top: { customer: string; totalPence: number }[];
errors: RowError[];
};
function buildReport(csv: string, topN = 3): Report {
const lines = csv.split(/\r?\n/).filter((l) => l.trim() !== "");
const errors: RowError[] = [];
const totalsByCustomer = new Map<string, number>();
lines.slice(1).forEach((text, index) => {
const lineNumber = index + 2;
const result = toOrder(parseCsvLine(text), lineNumber);
if ("reason" in result) {
errors.push(result);
return;
}
totalsByCustomer.set(
result.customer,
(totalsByCustomer.get(result.customer) ?? 0) + result.amountPence
);
});
const totals = [...totalsByCustomer]
.map(([customer, totalPence]) => ({ customer, totalPence }))
.sort((a, b) => b.totalPence - a.totalPence || a.customer.localeCompare(b.customer));
return { totals, top: totals.slice(0, topN), errors };
}/\r?\n/handles both Unix and Windows line endings.- Line numbers start at 2 because line 1 is the header. Users need exact line numbers to fix their files.
"reason" in resultnarrows the union (Lesson 106).- The sort has a tie-break by name, so the output is always the same order.
Result for the example
totals:
alice@example.com 122049 (£1,220.49)
bob@example.com 1250 (£12.50)
errors:
line 5: missing or invalid customer
line 6: invalid amount "abc"Extensions to mention
- Large files: read line by line with a stream instead of loading everything (Part 15).
- Duplicate order IDs: track seen IDs in a Set and report repeats.
- Validation library: Zod schemas for each row (Lesson 114).
- Output formats: write the report as CSV or JSON; format money with
Intl.NumberFormatonly at the end.
How to say it in an interview
"I split the task into parse, validate, aggregate and report functions so each can be tested. The CSV parser handles quoted fields and escaped quotes, though in production I'd use a library. Validation converts each row into a typed order or an error with its line number, so bad rows are reported rather than crashing the run. Money is converted to integer pence by string handling, customers are normalised to lower case, totals are summed in a Map, and the output is sorted with a tie-break so it is deterministic."
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.