Checkpoint: Data & Logic
Published by Brayan K
You've learned iterators, generators, strings, numbers, loops, conditionals and type coercion — let's combine them. Up to now each topic stood on its own. Real programs blend them: you loop over rows of text, slice and trim each field, convert strings to numbers, and branch on conditions to summarize the result.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Give the text format a deliberately small contract
Process a local text table with the header product,quantity,unitPriceMinor. Each data row has exactly three unquoted fields. Surrounding spaces are ignored, blank lines are skipped, and LF or CRLF line endings are accepted. Quantity and price must contain decimal digits only and become nonnegative safe integers; price is expressed in integer minor units.
This exercise is not a general CSV parser. Quoted commas, escaped quotes and multiline quoted fields need a parser that implements those rules; this table rejects quotes instead of silently splitting them incorrectly. The work here is to separate splitting, validation, calculation and reporting.
const row = " Notebook , 2 , 450 ";
const fields = row.split(",").map(field => field.trim());
// Conversion is appropriate for this already known-good demonstration row.
const [product, quantityText, priceText] = fields;
const quantity = Number(quantityText);
const unitPriceMinor = Number(priceText);
const lineTotalMinor = quantity * unitPriceMinor;
console.log(product);
console.log(quantity, unitPriceMinor, lineTotalMinor);
// ✅ Expected output:
// Notebook
// 2 450 900Strings & String Methods owns split and trim, while Numbers & Math owns numeric conversion. The checkpoint decides when those operations are safe for this input contract.
Check the field count before using a missing field
Destructuring does not invent a missing third field. Calling trim on the absent value produces an exception. Validate the row shape first so a bad row can receive a useful rejection reason rather than an accidental property-access error.
const [product, quantityText, priceText] = "Notebook,2".split(",");
console.log(priceText.trim());
// ✅ Expected error:
// TypeError: Cannot read properties of undefined (reading 'trim')function shapeProblem(line) {
if (line.includes('"')) return "quoted fields unsupported";
const fields = line.split(",").map(field => field.trim());
if (fields.length !== 3) return "expected three fields";
if (fields[0] === "") return "missing product";
return "shape accepted";
}
for (const line of ["Notebook,2,450", "Notebook,2", "Notebook,2,450,extra", '"Note,book",2,450', ",2,450"]) {
console.log(shapeProblem(line));
}
// ✅ Expected output:
// shape accepted
// expected three fields
// expected three fields
// quoted fields unsupported
// missing productA shape acceptance is not a numeric acceptance. Keep those stages separate so a diagnostic describes the first failed rule. Destructuring Assignment owns the binding behaviour that makes the missing field undefined.
Successful conversion is not the same as accepted input
Number accepts a wider grammar than this table, and blank text converts to zero. Test the allowed characters before conversion, then test the numeric range. Otherwise a missing quantity or exponent-form string could pass a rule intended for decimal digits.
for (const text of ["", " ", "0", "1e2", "7units"]) {
console.log(JSON.stringify(text), Number(text));
}
// ✅ Expected output:
// "" 0
// " " 0
// "0" 0
// "1e2" 100
// "7units" NaNfunction isDecimalText(text) {
if (text.length === 0) return false;
for (const character of text) {
if (!"0123456789".includes(character)) return false;
}
return true;
}
for (const text of ["", "0", "12", "1e2", "2.5", "-1", "9007199254740992"]) {
console.log(JSON.stringify(text), isDecimalText(text), Number.isSafeInteger(Number(text)));
}
// ✅ Expected output:
// "" false true
// "0" true true
// "12" true true
// "1e2" false true
// "2.5" false false
// "-1" false true
// "9007199254740992" true falseThe final sample has the allowed characters but is outside the safe-integer range. Type Coercion (== vs ===) owns conversion distinctions; this checkpoint combines grammar and range checks to enforce one particular table format.
Keep source line numbers when skipping blank lines
Report the line where the problem occurred, not the position after filtering out blanks. Normalize CRLF first, then enumerate the original split lines. Skip a blank line inside the loop so later line numbers still refer to the supplied text.
const text = "product,quantity,unitPriceMinor\r\nNotebook,2,450\r\n\r\nPen,0,99";
const lines = text.replaceAll("\r\n", "\n").split("\n");
for (const [index, raw] of lines.entries()) {
const line = raw.trim();
if (line === "") continue;
console.log(index + 1, line);
}
// ✅ Expected output:
// 1 product,quantity,unitPriceMinor
// 2 Notebook,2,450
// 4 Pen,0,99The first nonblank row must be the exact header after trimming its three fields. A later line that merely begins with the word product is not automatically another header. Loops & Iteration owns continue and iteration.
const firstLine = "name,quantity,price";
const header = firstLine.split(",").map(field => field.trim()).join(",");
if (header !== "product,quantity,unitPriceMinor") {
throw new Error("Expected product,quantity,unitPriceMinor header");
}
console.log("header accepted");
// ✅ Expected error:
// Error: Expected product,quantity,unitPriceMinor headerCheck arithmetic as well as each input number
Two safe integer inputs can still produce an unsafe product or accumulated total. Calculate a candidate line amount and candidate report total, then accept the row only if both remain safe integers. Valid zero quantities and prices stay valid.
const quantity = 2;
const unitPriceMinor = Number.MAX_SAFE_INTEGER;
const lineTotalMinor = quantity * unitPriceMinor;
console.log(Number.isSafeInteger(quantity), Number.isSafeInteger(unitPriceMinor));
console.log(Number.isSafeInteger(lineTotalMinor));
const existingTotal = Number.MAX_SAFE_INTEGER;
console.log(Number.isSafeInteger(existingTotal + 1));
console.log(Number.isSafeInteger(0 * 99));
// ✅ Expected output:
// true true
// false
// false
// trueThese checks define the numeric limits of this small report. The implementation keeps integer minor units for calculation; display formatting is a later presentation step and does not repair an already inaccurate total.
Keep a rejection visible instead of silently dropping it
A skipped blank line and a rejected data row are different outcomes. Return rejected line numbers and reasons alongside the accepted-row count. For the quantity ranking, this exercise chooses the largest accepted row, with ties keeping the earlier row; it does not claim to aggregate repeated product names into a best-selling product.
const rows = [
{ product: "Notebook", quantity: 2, line: 2 },
{ product: "Pen", quantity: 0, line: 3 },
{ product: "Notebook", quantity: 2, line: 7 }
];
let largestRow = null;
for (const row of rows) {
if (largestRow === null || row.quantity > largestRow.quantity) {
largestRow = row;
}
}
console.log(JSON.stringify(largestRow));
// ✅ Expected output:
// {"product":"Notebook","quantity":2,"line":2}If the product requirement is totals grouped by product, add an explicit grouping stage rather than relabelling this row maximum. Checkpoint: Core JavaScript practises keeping report fields and their input populations distinct.
Complete the shape, conversion and amount expressions
The supplied row has already been checked for the allowed digit grammar. Fill three expressions using the literal hints, keeping its zero quantity valid. This small exercise isolates the conversion and arithmetic stages before the complete report.
const fields = "Pen,0,99".split(",").map(field => field.trim());
if (fields.length !== ___) throw new Error("Expected three fields");
const [product, quantityText, priceText] = fields;
const quantity = ___;
const unitPriceMinor = Number(priceText);
const lineTotalMinor = ___;
// 👉 replace ___ with 3
// 👉 replace ___ with Number(quantityText)
// 👉 replace ___ with quantity * unitPriceMinor
console.log(product, quantity, lineTotalMinor);
console.log(Number.isSafeInteger(lineTotalMinor));
// ✅ Expected output:
// Pen 0 0
// trueBuild a report that explains which rows it rejected
Write parseReport(text) for the format defined above. Require the first nonblank line to be the header, skip later blank lines, and reject data rows in this order: quotes, field count, missing product, quantity grammar, price grammar, numeric range, then unsafe line/report amounts. Return accepted, rejected, totalMinor and largestRow. Rejected entries need the original line number and a reason. A rejected row must not affect totals or the ranking.
For header-only input, return zero accepted rows, an empty rejected list, a zero total and a null largestRow. Preserve the earlier row on quantity ties. Check the mixed fixture, header-only input and a CRLF zero-price row. These are local text fixtures; no file or network access is required.
function isDecimalText(text) {
if (text.length === 0) return false;
for (const character of text) {
if (!"0123456789".includes(character)) return false;
}
return true;
}
function parseReport(text) {
const lines = text.replaceAll("\r\n", "\n").split("\n");
const rejected = [];
let headerSeen = false, accepted = 0, totalMinor = 0, largestRow = null;
for (const [index, raw] of lines.entries()) {
const line = raw.trim();
if (line === "") continue;
const fields = line.split(",").map(field => field.trim());
if (!headerSeen) {
if (fields.join(",") !== "product,quantity,unitPriceMinor") {
throw new Error("Expected product,quantity,unitPriceMinor header");
}
headerSeen = true;
continue;
}
let reason = null;
if (line.includes('"')) reason = "quoted fields unsupported";
else if (fields.length !== 3) reason = "expected three fields";
else if (fields[0] === "") reason = "missing product";
else if (!isDecimalText(fields[1])) reason = "invalid quantity";
else if (!isDecimalText(fields[2])) reason = "invalid price";
if (reason !== null) {
rejected.push({ line: index + 1, reason });
continue;
}
const [product] = fields;
const quantity = Number(fields[1]), unitPriceMinor = Number(fields[2]);
if (!Number.isSafeInteger(quantity) || !Number.isSafeInteger(unitPriceMinor)) {
rejected.push({ line: index + 1, reason: "unsafe number" });
continue;
}
const lineTotalMinor = quantity * unitPriceMinor;
const candidateTotal = totalMinor + lineTotalMinor;
if (!Number.isSafeInteger(lineTotalMinor) || !Number.isSafeInteger(candidateTotal)) {
rejected.push({ line: index + 1, reason: "amount too large" });
continue;
}
accepted += 1;
totalMinor = candidateTotal;
if (largestRow === null || quantity > largestRow.quantity) {
largestRow = { product, quantity, line: index + 1 };
}
}
if (!headerSeen) throw new Error("Missing header");
return { accepted, rejected, totalMinor, largestRow };
}
const data = [
"product,quantity,unitPriceMinor",
"Notebook,2,450",
"Pen,0,99",
"",
"Bad, ,99",
"Huge,2,9007199254740991",
"Notebook,2,100",
'"Note,book",1,10',
"Extra,1,10,field"
].join("\n");
console.log(JSON.stringify(parseReport(data)));
console.log(JSON.stringify(parseReport("product,quantity,unitPriceMinor")));
console.log(JSON.stringify(parseReport("product,quantity,unitPriceMinor\r\nGift,3,0")));
// ✅ Expected output:
// {"accepted":3,"rejected":[{"line":5,"reason":"invalid quantity"},{"line":6,"reason":"amount too large"},{"line":8,"reason":"quoted fields unsupported"},{"line":9,"reason":"expected three fields"}],"totalMinor":1100,"largestRow":{"product":"Notebook","quantity":2,"line":2}}
// {"accepted":0,"rejected":[],"totalMinor":0,"largestRow":null}
// {"accepted":1,"rejected":[],"totalMinor":0,"largestRow":{"product":"Gift","quantity":3,"line":2}}The mixed result exposes rejection reasons and original line positions, not just a plausible final amount. To test a change, vary one rule at a time: remove a field, blank a quantity, add a quoted comma, introduce a tie, or make the total exceed the safe range. Keeping those cases small makes a failure easier to locate.
The RFC 4180 format description includes quoted fields and embedded separators. This exercise intentionally implements a smaller unquoted format and trims spaces by its own stated contract. For full CSV input, use a parser with explicit support for the required dialect.
Practice quiz
What does this complete program print? const [name, quantity, price] = "Pen,2".split(","); console.log(price === undefined);
- true
- false
- 2
- TypeError: price is not defined
Answer: true. A missing third field becomes undefined; destructuring does not add a price.
What does this complete program print? console.log(Number(""), Number("0"), Number("1e2"));
- NaN 0 NaN
- 0 0 100
- 0 0 NaN
- NaN 0 100
Answer: 0 0 100. Conversion accepts blank text and exponent syntax, so it is broader than the checkpoint’s digit grammar.
What does this complete program print? const text = "header Pen,0,99"; for (const [index, line] of text.split(" ").entries()) { if (line === "") continue; console.log(index + 1); }
- 1 2
- 0 2
- 1 3
- 1 2 3
Answer: 1 3. Skipping a blank inside the loop preserves the original source positions.
What does this complete program print? const quantity = 0, unitPriceMinor = 99; console.log(quantity * unitPriceMinor, Number.isSafeInteger(quantity));
- 99 true
- 0 false
- NaN false
- 0 true
Answer: 0 true. Zero is a valid whole quantity and produces a zero line total.
What does this complete program print? console.log(Number.isSafeInteger(2 * Number.MAX_SAFE_INTEGER));
- false
- true
- 2
- undefined
Answer: false. Safe inputs do not guarantee that their product remains a safe integer.
What does this complete program print? const first = { product: "A", quantity: 2 }; const second = { product: "B", quantity: 2 }; let best = first; if (second.quantity > best.quantity) best = second; console.log(best.product);
- B
- A
- undefined
- A,B
Answer: A. A strict greater-than comparison keeps the earlier row when quantities tie.
What does this complete program print? const line = "Pen,2,99,extra"; console.log(line.split(",").length === 3);
- true
- 3
- false
- undefined
Answer: false. The extra field violates the exact three-field shape.
What does this complete program print? const line = "\"Note,book\",1,10"; console.log(line.includes('"')); console.log(line.split(",").length);
- false 3
- true 3
- false 4
- true 4
Answer: true 4. Simple splitting treats the quoted comma as a separator; this exercise rejects quotes rather than treating that as valid CSV parsing.
Continue this course
- Previous: Checkpoint: Core JavaScript
- Next: DOM Manipulation — Select and change HTML elements directly from JavaScript
- Quick reference: JavaScript cheat sheet