Reading — step 1 of 5
Learn
Records and Maps
Programs constantly answer two questions: "what value goes with this key?" and "have I seen this before?" TypeScript gives you three tools — plain objects, Map, and Set — and knowing which to reach for is the actual skill.
Plain objects + Record
For simple string-keyed data, a plain object is perfect, and Record<K, V> is its type:
const ages: Record<string, number> = {
alice: 30,
bob: 25,
};
console.log(ages.alice); // 30
ages.carol = 40; // add a key
console.log(ages["bob"]); // bracket syntax for dynamic keys
Record<string, number> reads: "an object whose keys are strings and whose values are numbers." The compiler stops you from storing a string value or treating one as a boolean.
Map — the real hash map
const counts: Map<string, number> = new Map();
counts.set("go", 1);
counts.get("go"); // 1 — or undefined if the key is absent
counts.has("rust"); // false
counts.size; // 1
Choose Map over a plain object when you need non-string keys (objects, numbers), reliable insertion-order iteration, frequent adds and deletes, or an accurate .size (with objects you must count Object.keys(obj).length).
The counting idiom, built on nullish coalescing:
counts.set(word, (counts.get(word) ?? 0) + 1);
?? supplies a fallback ONLY when the left side is null or undefined. That is different from ||, which also falls back on 0 and "" — with ||, a legitimate count of 0 would be mistaken for "missing." For absent-vs-falsy decisions, ?? is the correct operator.
Set — membership and uniqueness
A Set<T> stores each value at most once:
const seen: Set<string> = new Set();
seen.add("the");
seen.add("quick");
seen.add("the"); // duplicate — silently ignored
console.log(seen.size); // 2, not 3
console.log(seen.has("quick")); // true
Adding a duplicate simply does nothing — no error, no second copy. That makes "count the distinct items" a one-line mental model: add everything, read .size. (You can even build a set straight from an array: new Set(words).)
The trap: Sets use .size, not .length. Arrays have .length; on a Set, seen.length is undefined. TypeScript will flag it — one more compile-time save.
Your exercise
The starter reads one line and splits it into words:
const words: string[] = require('fs').readFileSync(0, 'utf-8').trim().split(' ');
const seen: Set<string> = new Set();
Add each word to seen (a for...of loop or words.forEach(...) both work), then print seen.size.
The exact mistake the grader will catch: printing the TOTAL word count instead of the DISTINCT count. For input the quick brown the, words.length is 4, but the expected output is 3 — the duplicate the must collapse into one. And remember: it is seen.size, not seen.length. Print just the number.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…