These are the notes for JavaScript episode 39, the course capstone. No new syntax: we build one complete app from an empty file, using reading input, Maps, classes, sorting, errors and tests. Aman, Isha and Ravi come back from Goa and nobody knows who owes whom. Version 1 prints a balance of 400.00000000000006, so we keep money in whole paise. We settle up by matching the biggest debts with the biggest credits, wrap everything in a class Trip, discover that one typo (12OO) turns every balance into NaN silently, add input checks with line numbers, and finish with node:test. Every output below is real Node.js output (Node 24); the input goes in the compiler's input box (standard input).
Builds on: strings and split (episode 4), functions and default parameters (9), filter (11), spread and destructuring (12), errors and try/catch (13), reading stdin (14), classes (16), Map (21), testing with node:test (30), sorting (37). Leads to: interview questions and the road to React and Node backends (40).
The problem: the Goa trip
The expense log, one bill per line: who paid, how much (in rupees), what for.
Aman 1000 hotel
Isha 600 dinner
Ravi 200 chai
Everything is shared equally. Balance = what you paid − your share. Positive: the group owes you. Negative: you owe the group. All balances must add up to 0: money can't appear from nowhere.
Version 1: balances in rupees
const input = require("fs").readFileSync(0, "utf8");
const friends = ["Aman", "Isha", "Ravi"];
const balance = new Map(friends.map((f) => [f, 0]));
for (const line of input.trim().split("\n")) {
const [payer, amount] = line.split(" ");
const share = Number(amount) / friends.length;
balance.set(payer, balance.get(payer) + Number(amount));
for (const f of friends) balance.set(f, balance.get(f) - share);
}
console.log(balance);
console.log("total:", [...balance.values()].reduce((a, b) => a + b, 0));
Input: the three lines above. Output:
Map(3) {
'Aman' => 400.00000000000006,
'Isha' => 1.4210854715202004e-14,
'Ravi' => -399.99999999999994
}
total: 1.1368683772161603e-13
Why: 1000 / 3 = 333.333… forever. JavaScript numbers are binary floating-point (IEEE 754 doubles), and in binary most decimals never end, just like 1/3 in decimal. The computer stores the closest value it can, and the tiny errors pile up. It's the same reason 0.1 + 0.2 is 0.30000000000000004 (episode 2). 1.42e-14 means 1.42 × 10⁻¹⁴.
Money in paise: whole numbers are exact
No shopkeeper hands you a third of a paisa. Store paise: ₹1000 = 100000 paise, a whole number, and whole numbers (up to 2⁵³) are stored exactly. Banks and payment apps do the same (or use decimal libraries).
share = Math.floor(paise / n): everyone's base share.extra = paise % n: the odd paise left over; give one each to the firstextrafriends.- Convert to rupees only when printing:
(p / 100).toFixed(2).
const input = require("fs").readFileSync(0, "utf8");
const friends = ["Aman", "Isha", "Ravi"];
const balance = new Map(friends.map((f) => [f, 0]));
for (const line of input.trim().split("\n")) {
const [payer, amount] = line.split(" ");
const paise = Math.round(Number(amount) * 100);
const share = Math.floor(paise / friends.length);
let extra = paise % friends.length;
balance.set(payer, balance.get(payer) + paise);
for (const f of friends) {
const mine = share + (extra-- > 0 ? 1 : 0);
balance.set(f, balance.get(f) - mine);
}
}
const rs = (p) => "Rs " + (p / 100).toFixed(2);
for (const [f, p] of balance) console.log(f.padEnd(5), rs(p));
console.log("total:", [...balance.values()].reduce((a, b) => a + b, 0));
Output:
Aman Rs 399.99
Isha Rs 0.00
Ravi Rs -399.99
total: 0
The hotel (100000 paise) splits as 33334 + 33333 + 33333, and chai (20000) as 6667 + 6667 + 6666. Aman got the odd paisa from two bills, so his share is 1 paisa bigger and he gets back ₹399.99, not ₹400. Every paisa is counted: the total is exactly 0.
Math.round(Number(amount) * 100)turns "12.50" into 1250 safely (12.5 * 100might be 1249.9999… for other values; rounding fixes it).extra-- > 0compares first, then subtracts one (post-decrement, episode 3).padEnd(5)pads the name with spaces so the amounts line up.
Settling up: who pays whom
- Split people into those who owe (balance < 0) and those who are owed (balance > 0), with
filter. - Sort both groups, biggest amount first (episode 37).
- The biggest debtor pays the biggest creditor
min(debt, credit). That clears at least one of them; remove whoever reaches 0. Repeat.
Every payment clears at least one person, so n friends need at most n − 1 payments. (Finding the absolute minimum number of payments is a much harder problem; this greedy method is what most apps use and is never worse than n − 1.)
A Trip class
class Trip {
constructor(friends) {
this.balance = new Map(friends.map((f) => [f, 0]));
}
add(payer, paise, among = [...this.balance.keys()]) {
const share = Math.floor(paise / among.length);
let extra = paise % among.length;
this.balance.set(payer, this.balance.get(payer) + paise);
for (const f of among) {
const mine = share + (extra-- > 0 ? 1 : 0);
this.balance.set(f, this.balance.get(f) - mine);
}
}
settle() {
const all = [...this.balance].map(([name, p]) => ({ name, p }));
const owe = all.filter((x) => x.p < 0).sort((a, b) => a.p - b.p);
const get = all.filter((x) => x.p > 0).sort((a, b) => b.p - a.p);
const pays = [];
while (owe.length && get.length) {
const amount = Math.min(-owe[0].p, get[0].p);
pays.push(`${owe[0].name} pays ${get[0].name} ${rs(amount)}`);
owe[0].p += amount;
get[0].p -= amount;
if (owe[0].p === 0) owe.shift();
if (get[0].p === 0) get.shift();
}
return pays;
}
}
const rs = (p) => "Rs " + (p / 100).toFixed(2);
const input = require("fs").readFileSync(0, "utf8");
const trip = new Trip(["Aman", "Isha", "Ravi", "Neha"]);
for (const line of input.trim().split("\n")) {
const [payer, amount] = line.split(" ");
trip.add(payer, Math.round(Number(amount) * 100));
}
for (const [f, p] of trip.balance) console.log(f.padEnd(5), rs(p));
console.log(trip.settle().join("\n"));
Input:
Aman 2400 hotel
Isha 900 dinner
Ravi 300 cab
Output:
Aman Rs 1500.00
Isha Rs 0.00
Ravi Rs -600.00
Neha Rs -900.00
Neha pays Aman Rs 900.00
Ravi pays Aman Rs 600.00
among = [...this.balance.keys()]is a default parameter (episode 9): by default a bill is shared by everyone. Default values are worked out at call time, so they can usethis.[...this.balance]turns the Map into[name, paise]pairs;.map(([name, p]) => ({ name, p }))destructures each pair into an object.oweis sorted ascending (most negative first),getdescending (biggest first).- Because balances are whole paise,
owe[0].p === 0is reliable. With decimal rupees it might be1e-14and never exactly 0, so the loop could pair people wrongly or never shorten. rsis aconstdefined after the class; that's fine becausesettleonly runs later, afterrsexists.
Bad input: NaN spreads silently
Input (Neha typed the letter O twice):
Aman 2400 hotel
Isha 900 dinner
Neha 12OO shopping
Ravi 300 cab
Output of the same program:
Aman Rs NaN
Isha Rs NaN
Ravi Rs NaN
Neha Rs NaN
Why: Number("12OO") is NaN (Not a Number). NaN plus anything is NaN, so it spread through share into every balance. And NaN < 0 and NaN > 0 are both false, so both settle groups are empty and nothing is printed. No error, no warning: NaN never crashes, it spreads.
Check every line: parse, throw and try/catch
Like a bouncer at the door, every line is checked before it touches the balances.
function parse(line, n, trip) {
const [payer, amount, what, among] = line.trim().split(/\s+/);
if (!trip.balance.has(payer)) throw new Error(`line ${n}: who is "${payer}"?`);
const rupees = Number(amount);
if (!(rupees > 0)) throw new Error(`line ${n}: "${amount}" is not an amount`);
const names = among ? among.split(",") : undefined;
return [payer, Math.round(rupees * 100), names];
}
const input = require("fs").readFileSync(0, "utf8");
const trip = new Trip(["Aman", "Isha", "Ravi", "Neha"]);
input.trim().split("\n").forEach((line, i) => {
try {
trip.add(...parse(line, i + 1, trip));
} catch (err) {
console.log("skipped", err.message);
}
});
for (const [f, p] of trip.balance) console.log(f.padEnd(5), rs(p));
console.log(trip.settle().join("\n"));
(The Trip class and rs stay exactly as above.) Input:
Aman 2400 hotel
Isha 900 dinner
Ravi 300 cab Ravi,Neha
Neha 12OO shopping
Isha 100 chai Isha,Aman
Rahul 500 ice-cream
Output:
skipped line 4: "12OO" is not an amount
skipped line 6: who is "Rahul"?
Aman Rs 1525.00
Isha Rs 125.00
Ravi Rs -675.00
Neha Rs -975.00
Neha pays Aman Rs 975.00
Ravi pays Aman Rs 550.00
Ravi pays Isha Rs 125.00
split(/\s+/)splits on one or more spaces or tabs (a regular expression, episode 23), so extra spaces don't break a line.!(rupees > 0)is true forNaN(sinceNaN > 0is false), 0 and negative numbers. Writingrupees <= 0would letNaNthrough, becauseNaN <= 0is also false.- The optional fourth field
Ravi,Nehalists who shares that bill;undefinedlets the default parameter (everyone) apply. trip.add(...parse(...))spreads the returned array into the three arguments.try/catcharound each line: a bad line is skipped with a message that says which line and why, and the rest still counts.
Checking the math: Aman +2400 − 600 (hotel) − 225 (dinner) − 50 (chai) = +1525. Isha +900 − 600 − 225 + 100 − 50 = +125. Ravi −600 − 225 + 300 − 150 (cab) = −675. Neha −600 − 225 − 150 = −975. Total 0.
Tests with node:test
// the Trip class and rs as above
const test = require("node:test");
const assert = require("node:assert");
test("balances add up to zero", () => {
const trip = new Trip(["A", "B", "C"]);
trip.add("A", 100000);
trip.add("B", 1);
const total = [...trip.balance.values()].reduce((a, b) => a + b, 0);
assert.strictEqual(total, 0);
});
test("one payment settles two friends", () => {
const trip = new Trip(["A", "B"]);
trip.add("A", 50000);
assert.deepStrictEqual(trip.settle(), ["B pays A Rs 250.00"]);
});
Output (durations vary):
✔ balances add up to zero (0.790145ms)
✔ one payment settles two friends (0.827698ms)
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 7.546166
Test 1 uses awkward amounts (₹1000 and 1 paisa among three) on purpose: if anyone later stores rupees as decimals or forgets the odd paise, it fails at once. strictEqual checks ===; deepStrictEqual compares arrays and objects by content.
The whole course in one app
| Part of the app | Where you learned it |
|---|---|
readFileSync(0, "utf8"), split, trim |
episodes 4 and 14 |
Map of balances |
episode 21 |
whole-number money, 0.1 + 0.2 |
episode 2 |
filter, reduce, sort with compare functions |
episodes 11 and 37 |
class Trip, default parameters |
episodes 9 and 16 |
throw, try/catch |
episode 13 |
spread ..., destructuring [payer, amount] |
episode 12 |
node:test, assert |
episode 30 |
a regular expression /\s+/ |
episode 23 |
Common mistakes (and what really happens)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
| money as decimal rupees | 400.00000000000006, total not 0 |
binary floating point can't store most decimals exactly | whole paise; convert only to print |
Math.floor share without the remainder |
the total is a few paise off | the odd paise are lost | hand out paise % n one by one |
Number("12OO") unchecked |
Rs NaN for everyone, no payments |
NaN spreads; NaN < 0 and NaN > 0 are false |
if (!(x > 0)) throw ... |
checking x <= 0 instead of !(x > 0) |
NaN still gets through | NaN <= 0 is false |
!(x > 0) or Number.isFinite(x) && x > 0 |
| one bad line throws and stops the app | nothing is printed | no try/catch per line |
catch, skip, say which line |
parseInt("12OO") instead of Number |
12: the bill silently becomes ₹12 |
parseInt stops at the first bad character |
Number, which gives NaN for the whole string |
comparing decimal balances with === 0 |
settle pairs people wrongly | 1e-14 !== 0 |
whole paise |
| no tests on money code | old bugs come back after changes | nobody re-checks by hand | node:test with exact expected values |
Mini project: friendlier commands
Extend parse so the fourth field can leave people out (-Isha = everyone except Isha) and also rejects unknown names in the list:
function parse(line, n, trip) {
const [payer, amount, what, among] = line.trim().split(/\s+/);
if (!trip.balance.has(payer)) throw new Error(`line ${n}: who is "${payer}"?`);
const rupees = Number(amount);
if (!(rupees > 0)) throw new Error(`line ${n}: "${amount}" is not an amount`);
let names;
if (among?.startsWith("-")) {
const left = among.slice(1).split(",");
names = [...trip.balance.keys()].filter((f) => !left.includes(f));
} else if (among) {
names = among.split(",");
}
for (const f of names ?? []) {
if (!trip.balance.has(f)) throw new Error(`line ${n}: who is "${f}"?`);
}
return [payer, Math.round(rupees * 100), names];
}
const trip = new Trip(["Aman", "Isha", "Ravi"]);
trip.add(...parse("Aman 300 cab -Isha", 1, trip));
console.log(trip.balance);
try { parse("Aman 300 cab Aman,Rohan", 2, trip); } catch (err) { console.log(err.message); }
Output:
Map(3) { 'Aman' => 15000, 'Isha' => 0, 'Ravi' => -15000 }
line 2: who is "Rohan"?
among?.startsWith("-") uses optional chaining: if among is undefined, the whole expression is undefined instead of a crash. names ?? [] (nullish coalescing) loops over nothing when there is no list.
Practice
1. Print how much each friend spent (paid), next to the balances.
Solution
// Trip, rs and parse as in the episode
const input = require("fs").readFileSync(0, "utf8");
const trip = new Trip(["Aman", "Isha", "Ravi", "Neha"]);
const spent = new Map();
input.trim().split("\n").forEach((line, i) => {
try {
const [payer, paise, among] = parse(line, i + 1, trip);
trip.add(payer, paise, among);
spent.set(payer, (spent.get(payer) || 0) + paise);
} catch (err) {
console.log("skipped", err.message);
}
});
for (const [f, p] of spent) console.log(f, "spent", rs(p));
Output (with the messy log from the episode):
skipped line 4: "12OO" is not an amount
skipped line 6: who is "Rahul"?
Aman spent Rs 2400.00
Isha spent Rs 1000.00
Ravi spent Rs 300.00
Neha paid for nothing that was counted, so she has no entry.
2. Support Aman 300 cab -Isha (everyone except Isha). See the mini project above.
3. Write tests for the two skipped lines.
Solution
// Trip, rs and parse as in the episode
const test = require("node:test");
const assert = require("node:assert");
test("an unknown friend is rejected with the line number", () => {
const trip = new Trip(["Aman", "Isha"]);
assert.throws(() => parse("Rahul 500 ice-cream", 6, trip), { message: 'line 6: who is "Rahul"?' });
});
test("a typo in the amount is rejected", () => {
const trip = new Trip(["Aman", "Isha"]);
assert.throws(() => parse("Aman 12OO shopping", 4, trip), /not an amount/);
});
Output (first lines):
✔ an unknown friend is rejected with the line number (1.366226ms)
✔ a typo in the amount is rejected (0.283126ms)
ℹ tests 2
assert.throws passes when the function throws an error matching an object (exact message) or a regular expression.
4. Save the trip to trip.json and load it again (episodes 19 and 33).
Solution
// Trip and rs as in the episode
const fs = require("fs");
const trip = new Trip(["Aman", "Isha", "Ravi"]);
trip.add("Aman", 100000);
fs.writeFileSync("trip.json", JSON.stringify([...trip.balance]));
console.log(fs.readFileSync("trip.json", "utf8"));
const again = new Trip([]);
again.balance = new Map(JSON.parse(fs.readFileSync("trip.json", "utf8")));
console.log(again.settle());
Output:
[["Aman",66666],["Isha",-33333],["Ravi",-33333]]
[ 'Isha pays Aman Rs 333.33', 'Ravi pays Aman Rs 333.33' ]
JSON.stringify can't save a Map directly (it becomes {}), so save its entries as an array of pairs and rebuild the Map with new Map(pairs).
Quick quiz
const b = [500, NaN, -200];
const owe = b.filter((p) => p < 0);
const get = b.filter((p) => p > 0);
console.log(owe.length + get.length);
A. 3 B. 2 C. NaN D. 0
Answer
B: 2. NaN < 0 and NaN > 0 are both false, so NaN falls into neither group: owe is [-200], get is [500]. Node really prints 2. That is how Neha's NaN balance vanished from settle().
Interview questions
- Why is
0.1 + 0.2 !== 0.3in JavaScript, and how do you handle money? Numbers are IEEE 754 binary doubles, which can't represent most decimal fractions exactly. Store money in the smallest unit (paise, cents) as integers, or use a decimal library; format only for display. - What is
NaN, and how do you check for it? "Not a Number", the result of invalid number operations.NaN !== NaN, so useNumber.isNaN(x);Number.isFinite(x)rejects NaN and Infinity. Number("12OO")vsparseInt("12OO")?Numberconverts the whole string and givesNaN;parseIntreads digits until the first invalid character and gives12.- How would you split an amount fairly when it doesn't divide evenly? Integer division for the base share, then distribute the remainder one unit at a time (largest-remainder method).
- Why validate input at the boundary of a program? So bad data is rejected with a clear message where it enters, instead of spreading and causing wrong results far away.
- When are default parameters evaluated? At call time, each time the argument is missing, so they can use
thisand earlier parameters. - How do you serialise a
Mapto JSON?JSON.stringify([...map])(an array of entries), andnew Map(JSON.parse(text))to restore it. - What makes a good unit test for money code? Exact expected values, awkward inputs (remainders, one paisa), and invariants such as "balances sum to zero".
Glossary
| Term | Meaning | Example |
|---|---|---|
| capstone project | a final project that combines everything learned | the trip splitter |
| CLI (command line interface) app | a program used by typing in a terminal | node main.js < log.txt |
| standard input (stdin) | the text a program receives as input | the expense log in the input box |
| balance | what you paid minus your share | Aman: +1525 |
| floating point | how computers store decimals, approximately | 400.00000000000006 |
| IEEE 754 double | the 64-bit number format JavaScript uses | every number |
| paise | 1/100 of a rupee, the smallest unit | ₹1000 = 100000 paise |
| integer arithmetic | maths on whole numbers, exact | 100000 % 3 is 1 |
remainder % |
what is left after division | the odd paise |
toFixed(2) |
format a number with 2 decimal places | "1525.00" |
padEnd(n) |
pad a string with spaces to length n | "Ravi " |
| settle up | the payments that make every balance 0 | Neha pays Aman Rs 975.00 |
| creditor / debtor | someone who is owed / who owes | Aman / Neha |
| default parameter | a value used when an argument is missing | among = [...this.balance.keys()] |
NaN |
"Not a Number": an invalid number result | Number("12OO") |
| input validation | checking input before using it | parse |
throw / Error |
stop and report a problem | throw new Error("line 4: ...") |
try / catch |
run code and handle a thrown error | skip a bad line |
optional chaining ?. |
stop with undefined instead of crashing on undefined |
among?.startsWith("-") |
nullish coalescing ?? |
a fallback for null/undefined |
names ?? [] |
| unit test | a small automatic check of one piece of code | test("balances add up to zero", ...) |
| assertion | a check that fails the test if false | assert.strictEqual(total, 0) |
| invariant | something that must always be true | balances sum to 0 |
| serialise | turn data into text to save or send | JSON.stringify([...map]) |
Summary
- Read the log from stdin, keep balances in a Map, and check the total is 0.
- Decimal rupees give
400.00000000000006: keep money in whole paise and hand out the odd paise. - Settle up by sorting debtors and creditors biggest first and matching them: at most n − 1 payments.
- A class with a default parameter keeps the logic tidy.
- NaN spreads silently; validate every line with
!(x > 0), throw errors with line numbers, and catch per line. - Tests with
node:testguard the money when the code changes. - Next: the finale, interview questions and the road to React and Node backends.