A string id is not necessarily a usable or unique id. Normalize by trimming first, reject blanks, then check uniqueness across the decoded catalogue. Otherwise "b1" and " b1 " can enter as supposedly distinct identities and collide later.
A Set<string> stores unique string values. has checks membership and add records a value. This generic spelling restricts the stored element type; the runtime object is JavaScript's ordinary Set. The catalogue's duplicate check runs after row decoding so it sees normalized ids.
A decoder returning Book[] establishes per-row rules and cross-row rules. Keep those promises explicit: finite nonnegative integer pages, nonblank normalized text, and unique ids. TypeScript cannot infer a uniqueness invariant merely from id:string.
The small example below isolates identity policy. Day 7 combines it with the full record decoder and reports the row of the duplicate. Extra input fields are ignored through projection rather than copied into trusted records.
Predict, run, and explain
Write down what the program prints before you run it. Use Check types first; the program runs only when the real compiler accepts it.
function uniqueIds(ids: readonly string[]): boolean {
const seen = new Set<string>();
for (const raw of ids) {
const id = raw.trim();
if (id === "" || seen.has(id)) {
return false;
}
seen.add(id);
}
return true;
}
console.log(uniqueIds(["a", "b"]));
console.log(uniqueIds(["a", " a "]));Enable JavaScript to edit and type-check this example.
Check your prediction
true
falseNormalize before enforcing a cross-row invariant
Primitive field checks establish that each row is shaped correctly. They do not establish that ids are unique across the whole collection. Run relationship checks on normalized domain values, not raw spellings that the decoder will later change.
A Set<string> makes the chosen identity representation explicit. It cannot decide whether ids should be case-sensitive or whether leading spaces are meaningful. State those rules before adding values, and keep duplicate rejection separate from silently dropping duplicates.
function duplicate(ids: readonly string[]): boolean {
const seen = new Set<string>();
for (const raw of ids) {
const id = raw.trim();
if (seen.has(id)) {
return true;
}
seen.add(id);
}
return false;
}
console.log(duplicate(["a", " a "]));
console.log(duplicate(["a", "A"]));Enable JavaScript to edit and type-check this example.
Check your prediction
true
falseThis policy trims but preserves case. Lowercasing would create a different domain rule and needs deliberate tests rather than a casual cleanup change.
const ids = ["a", "a", "b"];
console.log(new Set(ids).size);
console.log(ids.length);
console.log(new Set(ids).size === ids.length);Enable JavaScript to edit and type-check this example.
Check your prediction
2
3
falseThe Set can reveal duplicates, but returning its contents would silently accept a shortened list. If the contract rejects duplicate identities, return a failure instead of deduplicated success.
Try the rule on new inputs
Test raw duplicates, padded duplicates, case differences and blanks. Identify which stage rejects each one. Explain why validating every row independently cannot prove the whole collection’s uniqueness.
Your turn
Domain Rules & Identity: practice
uniqueIds only answers yes or no, works only on bare strings, and hard-codes one identity rule. Day 7 needs more: the row number of the first duplicate, for any record type, under a rule the caller chooses. Write firstDuplicate(items, identity), where identity is a callback turning a record into its identity string, returning the index of the first row whose identity was already seen, or undefined. Use it to print 2 for books whose ids are "b1", " b2" and "b1 " (identity: trimmed id), then none and 1 for two members with emails "ada@example.com" and "Ada@Example.com", first with a case-sensitive identity and then a case-insensitive one.
// One generic helper; each caller passes its own identity rule.Enable JavaScript to edit and type-check this example.
Hint 1: the idea
The helper doesn't need to know what a book or a member is: a type parameter for the record and a callback from that type to string are enough. The normalization rule moves out of the helper and into each call.
Hint 2: a first step
Loop with items.entries() so you have the index, compute the identity once per row, and check the Set before adding to it.
Show one solution
function firstDuplicate<T>(
items: readonly T[],
identity: (item: T) => string
): number | undefined {
const seen = new Set<string>();
for (const [index, item] of items.entries()) {
const id = identity(item);
if (seen.has(id)) {
return index;
}
seen.add(id);
}
return undefined;
}
const books = [
{ id: "b1", title: "Types" },
{ id: " b2", title: "Maps" },
{ id: "b1 ", title: "Sets" }
];
const members = [{ email: "ada@example.com" }, { email: "Ada@Example.com" }];
console.log(firstDuplicate(books, book => book.id.trim()) ?? "none");
console.log(firstDuplicate(members, member => member.email.trim()) ?? "none");
console.log(
firstDuplicate(members, member => member.email.trim().toLowerCase()) ?? "none"
);Enable JavaScript to edit and type-check this example.
2
none
1T is inferred from each list, so inside book => book.id.trim() the checker knows book has an id, and the members call gets its own record type from the same helper. The return type number | undefined makes callers handle "no duplicate" (here with ??), and index 0 is a real answer that a truthiness test would lose. The policy the types can't express is the identity rule: the two member calls differ only in .toLowerCase(), and the none/1 lines are the evidence of which rule each one applied.
Change it and test it
Change the implementation to check raw ids before normalization and find a test that fails. Explain whether duplicate titles should be rejected too; that is a different domain decision, not something a generic uniqueness helper should assume.
Completion is saved in this browser only. It does not measure mastery.