← Fundamentals
Fundamentals

Sets and uniqueness

Which membership question is being answered?

Choose the equality rule and observation time behind a uniqueness report.

Outcome

Use native membership and insertion results correctly, then preserve recent uniqueness when repeated occurrences expire.

Terminology (4)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Membership
Whether an equivalent value has one representation in a set.
Cardinality
The number of distinct set members, rather than the number of input occurrences.
Insertion status
An operation result describing whether a member was newly added, which may differ from a prior-membership flag.
Live occurrence
An event position still included in the current recent-history window.

Membership and occurrences

A set answers whether a value is a member under its equality rule. It keeps one member for each distinct value, rather than a separate record for every occurrence. The chosen representation determines what counts as equal and which ordering guarantees, if any, apply.

A membership question also needs a time boundary: registered now, observed before this event, and present in a recent window describe different collections. Choose the required history first, then inspect what the native insertion, lookup or removal operation reports.

01Membership and cardinality

Count registered codes rather than registration rows

A badge scanner first checks codes against a registration list. Its event log also needs to say whether a code has appeared before. For repeated-scan monitoring, that all-time history is too broad: only the previous few event positions should count.

The registry imports codes 2, 2, 5. Repeating a registration should not create another distinct badge code. Predict its member count and its answer to the probe for code 2.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const seen = new Set([2, 2, 5]);

console.log("members", seen.size, "known", seen.has(2));
Which report prints?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc main.ts --noEmit --skipLibCheck --target es2022 --module nodenext --types node && node main.ts

Save one complete example at a time in a fresh folder under the selected filename. Run the shown checking/build command before execution. The browser lab supplies its editor, stdin fixtures and native runner.

02The meaning of an insertion result

Inspect the result of recording a code

The event log records code 4 in an existing history collection. The selected probe displays what its native recording and membership operations actually return. Predict the reports before interpreting them for a scan log.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const seen = new Set([2]);
const first = Boolean(seen.add(4));
const second = Boolean(seen.add(4));

console.log("results", first, second);
Which report prints?

03Uniqueness and expiring occurrences

Decide what remains when one occurrence expires

The scanner’s recent report counts event positions rather than registered seeds. Before implementing that policy, check the container behavior: insert code 4 twice, then remove it once. Predict the set’s member counts.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const active = new Set<number>();
active.add(4);
active.add(4);
const before = active.size;

active.delete(4);

console.log("before", before, "after", active.size);
Which report prints?
Loading A set member does not retain an occurrence count…

04Practice

Repair the badge scanner

Continue the scanner’s three reports: registration membership, all-time scan history and a recent-event window. The complete input reader and event scheduler are supplied. Input is width, probe, registered-code count and codes, then event count and event codes.

Registered codes seed ever history but do not seed recent history. Each recent flag concerns the previous width event positions; retained state must support the next call as well. The supplied finite inputs are well formed, widths and lengths are nonnegative, and codes and occurrence counts fit the shown integer types. Reader validation is outside the task.

Start the lab

Check registration, reconcile event flags with retained history, then maintain recent membership as event positions leave the window.

  1. easy · F-SET-V4-1 Observe registration
  2. medium · F-SET-V4-2 Record and classify history
  3. hard · F-SET-V4-3 Preserve recent uniqueness
In the frontend Use membership for a selected badge and cardinality for the selected-code count. Optional

A badge-selection control needs one selection per code, even when the same code appears repeatedly in an imported list. Set.has determines the button’s pressed state; Set.size counts selected codes. Publish a replacement set when a click changes the selection.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
'use client';

import { useState } from 'react';

export function BadgeSelection() {
	const [selected, setSelected] = useState(() => new Set([2]));

	function toggle() {
		setSelected((previous) => {
			const next = new Set(previous);

			if (next.has(4)) next.delete(4);
			else next.add(4);

			return next;
		});
	}

	return (
		<>
			<button aria-pressed={selected.has(4)} onClick={toggle}>
				Badge 4
			</button>
			<p>{selected.size} codes selected</p>
		</>
	);
}

The updater copies the previous Set and returns the changed replacement. The prior state is preserved, while has and size read the new selection. The add return value is never used as a boolean.

Sources: React: useState update identity and updater functions,Svelte: deep state boundaries,Svelte: reactive collections.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.