Skip to content
HopperHopper

Course navigation

Phase 5 · CapstoneDay 24

Build

  • About 75 minutes
  • 7 sections
  • Runnable TypeScript examples

Before you start

About 75 minutes

By the end you will be able to

  1. Build the remaining must-have features one at a time, checking and running the app after each.
  2. Validate every form input and show each problem next to the form.
  3. Load saved data safely, falling back to a starter deck when it is missing or broken.
  4. Write at least five Vitest tests for the app's core logic, and stop adding features when the hour ends.

What to remember from earlier

Yesterday you planned your app and built one feature all the way through. Today you build the rest of the must-have list. There is no new reading and nothing new to learn: every step uses Days 1 to 23.

Today’s hour is all building. Before you start, set a timer for 60 minutes. When it goes off, you stop adding features, even in the middle of one, and spend whatever is left on the self-check in 24.7. Day 25 is for fixing and polishing, not for features you did not finish today.

As yesterday, the examples build the flashcard app. If you chose another project, each milestone says what the matching step is for yours. Type your own code, and compare with the examples after each milestone. The complete flashcard app is under Putting it together.

Section 1 of 7

24.1 Today’s Plan

Open PLAN.md and number your must-haves in the order you will build them. Build first whatever the others depend on. For flashcards:

Order Must have Touches Milestone
1 Add a card, with clear errors parseCardInput, renderErrors, the submit event 24.2
2 Save and load; a starter deck the first time storage.ts, public/starter.json, start() 24.3
3 Delete a card removeCard, a Delete button, a delegated click 24.4
4 Study mode and the score recordAnswer, nextStudy, score, two renders 24.5
5 At least five tests cards.spec.ts, storage.spec.ts 24.6

Saving comes second because everything after it changes the deck, and you want to see each change survive a reload as soon as you make it.

For each feature, go round the same loop until it works:

  1. Write the data function in the data module, if the feature needs one. Try it with a line in cards-demo.ts and node src/cards-demo.ts.
  2. Write or extend the render function.
  3. Wire the event in main.ts.
  4. Run npm run check. Fix every error before you look at the page.
  5. Look at the page with npm run dev running, and try the feature, including the wrong ways to use it.

Do not start the next feature until the loop is finished for this one. Half-built features are the reason projects never finish: the app stops working, and you no longer know which change broke it.

Key idea

One feature at a time, and the app works after each one: npm run check is clean and the feature does what the plan says in the browser. Then, and only then, the next feature.

Section 2 of 7

24.2 Milestone 1: Validate the Form

Goal: the form refuses an empty or too-long card and lists every problem under the form; a valid card is added with its spaces trimmed off.

On Day 23, clicking Add card with empty boxes added an empty card. The fix belongs in the data module, as a function that takes the two strings from the form and returns Day 16’s result union, with a list errors in place of the single error string: either the cleaned-up input, or every problem at once. Add Result and parseCardInput to cards.ts:

/** A value, or every reason there is no value. */
export type Result<T> = { ok: true; value: T } | { ok: false; errors: string[] };

/** The most characters one side of a card may have. */
export const MAX_LENGTH = 80;

/** Trims both sides of a new card and checks them, reporting every problem at once. */
export function parseCardInput(front: string, back: string): Result<CardInput> {
  const input = { front: front.trim(), back: back.trim() };
  const errors: string[] = [];
  if (input.front === "") {
    errors.push("Write a question on the front.");
  }
  if (input.back === "") {
    errors.push("Write an answer on the back.");
  }
  if (input.front.length > MAX_LENGTH || input.back.length > MAX_LENGTH) {
    errors.push(`Keep each side to ${MAX_LENGTH} characters or fewer.`);
  }
  if (errors.length > 0) {
    return { ok: false, errors };
  }
  return { ok: true, value: input };
}

It trims first, so a box holding only spaces counts as empty. Each check adds to errors instead of returning straight away, so a person who leaves both boxes empty learns about both at once (Day 20).

Try it in the terminal before the page. Change cards-demo.ts to call it:

flashcards/cards-demo.ts
import { addCard, parseCardInput, recordAnswer, score } from "./cards.ts";

console.log(parseCardInput("  const ", "Cannot be reassigned"));
console.log(parseCardInput("", "   "));

let cards = addCard([], { front: "const", back: "Cannot be reassigned" });
cards = addCard(cards, { front: "string[]", back: "An array of strings" });
cards = recordAnswer(cards, 1, true);
cards = recordAnswer(cards, 2, false);
cards = recordAnswer(cards, 2, true);
console.log(score(cards));
{ ok: true, value: { front: 'const', back: 'Cannot be reassigned' } }
{
  ok: false,
  errors: [ 'Write a question on the front.', 'Write an answer on the back.' ]
}
{ right: 2, wrong: 1, percent: 67 }

The first call trimmed " const " to "const". The second reported both problems. (The last line comes from Milestone 4’s functions; ignore it until then.)

Now the page. Add an error list inside the form, under the button, with aria-live="polite" so a screen reader announces new errors:

<ul id="errors" aria-live="polite"></ul>

Add renderErrors to render.ts; it is renderCards again, one <li> per message. In main.ts, find the list, call renderErrors(errorList, state.errors) from render(), and change the submit listener so it checks before it adds:

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const result = parseCardInput(frontInput.value, backInput.value);
  if (!result.ok) {
    state.errors = result.errors;
    render();
    return;
  }
  state.cards = addCard(state.cards, result.value);
  state.errors = [];
  frontInput.value = "";
  backInput.value = "";
  frontInput.focus();
  render();
});

After if (!result.ok) { … return; }, the checker has narrowed result to the ok: true member, so result.value is a CardInput. A failed submit keeps what the person typed in the boxes, so they can fix it rather than retype it; a successful one clears the old errors.

Test it: type any in Front, leave Back empty, and click Add card. The list under the button shows one error, and no card is added:

<ul id="errors" aria-live="polite">
  <li>Write an answer on the back.</li>
</ul>

Your project: every form gets a parse… function in the data module that returns a Result. A budget entry’s amount is the one to be careful with: Number("") is 0 and Number("ten") is NaN, and both are numbers, so check with Number.isNaN and check that the amount is greater than 0.

Pause and try

Question 1 · Tracing

Predict exactly what this prints.

flashcards/predict-parse.ts
import { parseCardInput } from "./cards.ts";

const result = parseCardInput("   ", "x".repeat(81));
if (result.ok) {
  console.log(`Added: ${result.value.front}`);
} else {
  console.log(`${result.errors.length} problems:`);
  for (const error of result.errors) {
    console.log(`- ${error}`);
  }
}
Check your reasoning
2 problems:
- Write a question on the front.
- Keep each side to 80 characters or fewer.

" ".trim() is "", so the first check adds the front message. The back is 81 xs, which is not empty, so there is no back message, but 81 is more than MAX_LENGTH, so the third check adds the length message. With two errors, the function returns ok: false, and the else branch prints the count and each message.

Reread 24.2 Milestone 1: Validate the Form if you predicted a different number of problems.

Section 3 of 7

24.3 Milestone 2: Save, Load, and the Starter Deck

Goal: the deck survives a reload. The very first visit, and any visit where the saved data is broken, starts from a starter deck in public/starter.json.

This is Day 21’s pattern in its own module. First, a type guard in cards.ts, because it is about cards, not about storage:

/** True when value has every property a Card needs, each with the right type. */
export function isCard(value: unknown): value is Card {
  return (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    typeof value.id === "number" &&
    "front" in value &&
    typeof value.front === "string" &&
    "back" in value &&
    typeof value.back === "string" &&
    "right" in value &&
    typeof value.right === "number" &&
    "wrong" in value &&
    typeof value.wrong === "number"
  );
}

/** True when value is an array of cards. */
export function isCardList(value: unknown): value is Card[] {
  return Array.isArray(value) && value.every(isCard);
}

Then storage.ts, filling in the three functions from the plan:

flashcards/storage.ts
import { isCardList } from "./cards.ts";
import type { Card } from "./cards.ts";

const STORAGE_KEY = "flashcards";

/** The saved cards, or null when nothing is saved or the saved text is broken. */
export function loadCards(): Card[] | null {
  const text = localStorage.getItem(STORAGE_KEY);
  if (text === null) {
    return null;
  }
  try {
    const data: unknown = JSON.parse(text);
    return isCardList(data) ? data : null;
  } catch {
    return null;
  }
}

/** Saves the cards, replacing what was saved before. */
export function saveCards(cards: Card[]): void {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(cards));
}

/** The starter deck from public/starter.json, or an empty deck if it cannot be loaded. */
export async function loadStarter(): Promise<Card[]> {
  try {
    const response = await fetch("/starter.json");
    if (!response.ok) {
      return [];
    }
    const data: unknown = await response.json();
    return isCardList(data) ? data : [];
  } catch {
    return [];
  }
}
  • loadCards returns null in three cases: nothing saved (line 9), text that is not JSON at all, which makes JSON.parse throw (line 15), and JSON that is not a list of cards (line 14). catch with no (error) after it is allowed when the code does not need the error. Whatever went wrong, the caller gets one simple answer: no usable saved deck.
  • saveCards turns the deck into a string, because localStorage stores only strings.
  • loadStarter fetches the starter deck. Vite serves every file in the project’s public/ folder at the site’s root, so public/starter.json is at /starter.json. It checks the JSON with the same guard, and gives an empty deck if anything fails, so the app still opens.

Create public/starter.json with a few cards:

[
  { "id": 1, "front": "const", "back": "A variable that cannot be reassigned", "right": 0, "wrong": 0 },
  { "id": 2, "front": "string[]", "back": "An array of strings", "right": 0, "wrong": 0 },
  { "id": 3, "front": "unknown", "back": "A type you must narrow before using", "right": 0, "wrong": 0 }
]

In main.ts, the state now starts with an empty deck, and an async function fills it once the data is loaded:

const state: AppState = { cards: [], study: null, errors: [] };

async function start(): Promise<void> {
  state.cards = loadCards() ?? (await loadStarter());
  saveAndRender();
}

start();

?? uses its right side only when its left side is null or undefined, so the starter deck is fetched only when there is no usable save. Then add a saveAndRender() function that calls saveCards(state.cards) and then render(), and call it everywhere the deck changes, starting with the submit listener’s last line. Keep plain render() for changes that need no saving, such as showing errors.

Test it: reload the page after adding a card; the card is still there. Then break the save on purpose. In the browser’s developer tools (F12), open the Application tab (Storage in Firefox), find Local Storage, and change the flashcards value to {oops. Reload: JSON.parse throws, loadCards returns null, and the page shows the three starter cards instead of crashing. The app checked here was given exactly that broken save, and its list showed:

<ul id="cards">
  <li>
    <span>const → A variable that cannot be reassigned</span>
    <button type="button" data-id="1" aria-label="Delete const">Delete</button>
  </li>
  <li>
    <span>string[] → An array of strings</span>
    <button type="button" data-id="2" aria-label="Delete string[]">Delete</button>
  </li>
  <li>
    <span>unknown → A type you must narrow before using</span>
    <button type="button" data-id="3" aria-label="Delete unknown">Delete</button>
  </li>
</ul>

(The Delete buttons come from the next milestone.)

Your project: the same three functions with your item type, and a type guard for one item. For a recipe, the guard must also check each ingredient inside it: write isIngredient, then check Array.isArray(value.ingredients) && value.ingredients.every(isIngredient).

Watch out

Trusting the saved data. const cards: Card[] = JSON.parse(text) passes npm run check, because JSON.parse returns any. But the saved text can be anything: an older version of your app saved items without a field you added today, or someone edited it in the developer tools. A missing front means card.front.trim() crashes later, far from the cause. Give the result the type unknown and let the type guard decide (Day 16).

Pause and try

Question 2 · Multiple choice

loadCards returns null when nothing is saved, and the caller then loads the starter deck. Why not have it return an empty array [] instead?

  1. localStorage.getItem cannot return an empty array
  2. A person who deletes every card saves []; if “nothing saved” were also [], the app could not tell the two apart and would either refill the deck they emptied or never load the starter deck
  3. The checker does not allow a function to return an empty array
  4. null uses less space in localStorage
Check your reasoning

B. Two different situations need two different answers. “Nothing saved” means a first visit, so the starter deck is right. “An empty list was saved” means the person deleted every card on purpose, and the app should respect that. Card[] | null keeps them apart: [] is a real, valid save, and null means “no usable save.”

  • A is true but beside the point: loadCards decides what to return, whatever getItem gives it.
  • C is wrong: [] is a perfectly good Card[].
  • D is wrong: loadCards returns null to its caller; nothing is written to localStorage at all.

Reread 24.3 Milestone 2: Save, Load, and the Starter Deck if you chose differently.

Section 4 of 7

24.4 Milestone 3: Delete a Card

Goal: each card in the list has a Delete button, and clicking it removes that card and saves the deck.

The data side is one line: removeCard returns a new deck without the card that has the id, using filter. The page side has two parts. In renderCards, each <li> gets a <button> that remembers which card it belongs to in a data-id attribute:

const remove = document.createElement("button");
remove.type = "button";
remove.textContent = "Delete";
remove.setAttribute("data-id", String(card.id));
remove.setAttribute("aria-label", `Delete ${card.front}`);
item.append(text, remove);

type = "button" stops the button from submitting a form. Every button says “Delete,” so a screen reader user moving through the list would hear “Delete, Delete, Delete”; aria-label gives each one a full name, such as “Delete const.” The card’s text moves into a <span> so it sits next to its button.

Then one listener on the list, as on Day 19, instead of one per button. The buttons are rebuilt on every render, so listeners attached to them would have to be re-attached each time; the list itself is never replaced.

cardList.addEventListener("click", (event) => {
  const target = event.target;
  if (!(target instanceof HTMLButtonElement)) {
    return;
  }
  state.cards = removeCard(state.cards, Number(target.getAttribute("data-id")));
  state.study = null;
  saveAndRender();
});

A click on the card’s text has a <span> as its target, so the instanceof check ignores it. getAttribute returns a string (or null), and Number turns it back into the id. Setting state.study to null ends any study round in progress, because the card being studied might be the one just deleted.

Your project: the same pattern for any button inside a list, such as a habit’s day boxes. When a list item has more than one button, give each a data-action attribute as well, and check it in the listener, as Milestone 4 does.

Section 5 of 7

24.5 Milestone 4: Study Mode and the Score

Goal: a Study button starts a round. The page shows one card’s front; Show answer reveals the back; Got it or Missed it records the answer and moves on; after the last card the round ends. A line under the panel shows the running score.

This is the biggest feature, so build it in the loop’s order. The data functions first: recordAnswer returns a new deck in which one card’s right or wrong count is one higher, and nextStudy moves to the next position or returns null after the last card. score adds up every card’s counts. All three are in the complete cards.ts under Putting it together; try to write them from their signatures in your plan first.

Then the page. Add a Study button, an empty <section id="study-panel" aria-live="polite"> for the round, and a <p id="score"> to index.html. renderStudy draws the panel from state.study: nothing when it is null; otherwise a heading such as “Card 1 of 3,” the front, and either a Show answer button or the back with Got it and Missed it. Each of those buttons has a data-action attribute (show, right or wrong), and one delegated listener on the panel reads it:

studyPanel.addEventListener("click", (event) => {
  const target = event.target;
  const study = state.study;
  if (!(target instanceof HTMLButtonElement) || study === null) {
    return;
  }
  const action = target.getAttribute("data-action");
  if (action === "show") {
    state.study = { position: study.position, showingAnswer: true };
  } else {
    const card = state.cards[study.position];
    state.cards = recordAnswer(state.cards, card.id, action === "right");
    state.study = nextStudy(study, state.cards.length);
  }
  saveAndRender();
  focusStudy();
});

Every click replaces the panel’s buttons with new ones, and the button that had keyboard focus disappears with them. focusStudy() moves focus to the panel’s first new button, or back to Study when the round is over, so a keyboard user can keep pressing Enter through a whole round. Day 25 checks this with the keyboard.

In render(), call renderStudy and renderScore, and switch off the Study button when there are no cards: studyButton.disabled = state.cards.length === 0.

Test it: the app checked here started from a saved deck of three cards. Deleting string[], then clicking Study, Show answer, Got it, Show answer and Missed it left two cards, an empty panel because the round was over, and this score:

<p id="score">Score: 1 right, 1 wrong (50%)</p>

Your project: the “mode” in your app is whatever changes what the page shows without changing the saved data: the week a habit grid shows, the budget’s filter and sort, the recipe search and serving count. Keep it in the state, never in the saved data, and let render() read it.

Pause and try

Question 3 · Tracing

A fresh deck has three cards, none answered yet. A person clicks Study, then Show answer, Got it, Show answer, Got it, Show answer, Missed it. What does the score line say, and what does the study panel show?

Check your reasoning

The score line says Score: 2 right, 1 wrong (67%), and the panel is empty.

Click state.study Effect
Study { position: 0, showingAnswer: false } Card 1 of 3, front only
Show answer { position: 0, showingAnswer: true } Card 1’s back appears
Got it { position: 1, showingAnswer: false } Card 1 gets right: 1; card 2 of 3
Show answer { position: 1, showingAnswer: true } Card 2’s back appears
Got it { position: 2, showingAnswer: false } Card 2 gets right: 1; card 3 of 3
Show answer { position: 2, showingAnswer: true } Card 3’s back appears
Missed it null Card 3 gets wrong: 1; nextStudy ends the round

nextStudy returns null because position 3 is not less than 3 cards, and renderStudy draws nothing for null. score totals 2 right and 1 wrong; 2 / 3 × 100 is 66.67, which Math.round makes 67.

Reread 24.5 Milestone 4: Study Mode and the Score if your trace differed.

Section 6 of 7

24.6 Milestone 5: Five Tests

Goal: at least five passing Vitest tests for the app’s core logic, run with npm test.

Test the data module first: it is where the rules live, and its functions need no page (Day 22). Aim each test at a rule from your plan, especially the edge cases: the empty deck, the empty box, the last card, the broken save. Here are the flashcard app’s tests, more than five:

flashcards/cards.spec.ts
import { describe, expect, it } from "vitest";
import { addCard, isCardList, nextStudy, parseCardInput, recordAnswer, removeCard, score } from "./cards.ts";
import type { Card } from "./cards.ts";

const deck: Card[] = [
  { id: 1, front: "const", back: "Cannot be reassigned", right: 2, wrong: 0 },
  { id: 2, front: "string[]", back: "An array of strings", right: 1, wrong: 1 },
];

describe("parseCardInput", () => {
  it("trims both sides of a valid card", () => {
    expect(parseCardInput("  unknown ", " Check before use ")).toEqual({
      ok: true,
      value: { front: "unknown", back: "Check before use" },
    });
  });

  it("reports both empty sides at once", () => {
    expect(parseCardInput("   ", "")).toEqual({
      ok: false,
      errors: ["Write a question on the front.", "Write an answer on the back."],
    });
  });

  it("rejects a side longer than 80 characters", () => {
    expect(parseCardInput("a".repeat(81), "b").ok).toBe(false);
  });
});

describe("addCard and removeCard", () => {
  it("gives a new card the next id after the biggest one", () => {
    const cards = addCard(removeCard(deck, 1), { front: "any", back: "Turns checking off" });
    expect(cards.map((card) => card.id)).toEqual([2, 3]);
  });

  it("leaves the original deck unchanged", () => {
    removeCard(deck, 1);
    expect(deck.length).toBe(2);
  });
});

describe("recordAnswer and score", () => {
  it("counts a right answer on the right card", () => {
    expect(score(recordAnswer(deck, 2, true))).toEqual({ right: 4, wrong: 1, percent: 80 });
  });

  it("gives 0 percent before any answers", () => {
    expect(score([]).percent).toBe(0);
  });
});

describe("nextStudy", () => {
  it("moves to the next card with its answer hidden", () => {
    expect(nextStudy({ position: 0, showingAnswer: true }, 2)).toEqual({ position: 1, showingAnswer: false });
  });

  it("ends the round after the last card", () => {
    expect(nextStudy({ position: 1, showingAnswer: true }, 2)).toBe(null);
  });
});

describe("isCardList", () => {
  it("rejects a card with a missing property", () => {
    expect(isCardList([{ id: 1, front: "const", back: "Cannot be reassigned" }])).toBe(false);
  });
});

Notice what they check. “Gives a new card the next id after the biggest one” removes card 1 and then adds a card: the new card must get id 3, not 2, or two cards could end up sharing an id. “Leaves the original deck unchanged” checks the plan’s promise that data functions return new arrays. “Gives 0 percent before any answers” is the division-by-zero edge case from Day 12.

Storage needs localStorage, so its tests run in the jsdom environment, named in the comment on the first line:

flashcards/storage.spec.ts
// @vitest-environment jsdom
import { describe, expect, it } from "vitest";
import { loadCards, saveCards } from "./storage.ts";

describe("loadCards", () => {
  it("gives null when nothing is saved", () => {
    localStorage.clear();
    expect(loadCards()).toBe(null);
  });

  it("gives null when the saved text is not JSON", () => {
    localStorage.setItem("flashcards", "{oops");
    expect(loadCards()).toBe(null);
  });

  it("gives null when the saved JSON is not a list of cards", () => {
    localStorage.setItem("flashcards", '[{"front":"const"}]');
    expect(loadCards()).toBe(null);
  });

  it("gives back exactly what saveCards saved", () => {
    const cards = [{ id: 1, front: "const", back: "Cannot be reassigned", right: 0, wrong: 0 }];
    saveCards(cards);
    expect(loadCards()).toEqual(cards);
  });
});

The first test calls localStorage.clear() (Day 21) so it starts from a first visit; the others set the saved value themselves. The second and third tests are this morning’s “break the save on purpose” check, now repeated automatically every time you run npm test.

npm test runs every *.spec.ts file in src/, and all the tests above pass. If one of yours fails, read its output from the top, as on Day 22: the test’s name says which rule broke, and the expected and received values say how.

Pause and try

Question 4 · Short answer

Write one more test, in a new file remove.spec.ts, that checks that removeCard with an id that no card has leaves the deck the same.

Check your reasoning

One possible test:

flashcards/remove.spec.ts
import { describe, expect, it } from "vitest";
import { removeCard } from "./cards.ts";
import type { Card } from "./cards.ts";

describe("removeCard", () => {
  it("leaves the deck the same when no card has the id", () => {
    const deck: Card[] = [{ id: 1, front: "const", back: "Cannot be reassigned", right: 0, wrong: 0 }];
    expect(removeCard(deck, 99)).toEqual(deck);
  });
});

It builds a one-card deck, removes id 99, and checks the result with toEqual, which compares contents, so it passes even though filter returned a new array. toBe would fail here: it checks for the very same array, and removeCard always returns a new one. A good answer uses an id that is clearly not in the deck and compares the whole result, not only its length.

Reread 24.6 Milestone 5: Five Tests if your test differed in an important way.

Section 7 of 7

24.7 Stop and Self-Check

When the timer goes off, stop. A feature you did not finish moves to the “nice to have” list in PLAN.md, with a note of where you got to; if you left it half-built, undo it so the app works again. Then check the app against this table and write down anything that does not match. Day 25 starts from that list.

Try Should happen
npm run check No errors
npm test At least five tests, all passing
Submit the form with both boxes empty Both errors listed; nothing added
Submit 81 characters on one side The length error; nothing added
Add a card, then reload The card is still there
Set the saved value to {oops in the developer tools The starter deck, no crash
Delete every card, then reload Still empty: the starter deck does not come back
Delete a card during a study round The round ends; no error in the console
Study a whole round Each card once; the score matches what you clicked
Search cards.ts for document and localStorage Nothing: the data module never touches the page
  • Every must-have feature is built, or moved to nice-to-have with a note. Reread
  • The form validates its input and lists every problem in an aria-live list. Reread
  • The data is saved after every change and loaded safely, with a fallback for missing or broken data. Reread
  • Buttons inside a list use one delegated listener and a data attribute. Reread
  • The app has a mode that lives in the state but not in the saved data. Reread
  • At least five tests pass, including edge cases and broken saved data. Reread
Wrap-up · 1 of 3

Putting it together

Here is the complete flashcard app at the end of Day 24: one correct way, not the only one. First the <body> of index.html, above Vite’s <script> line:

index.html (inside body)
<main>
  <h1>Flashcards</h1>
  <form id="card-form">
    <label for="front">Front</label>
    <input id="front" name="front">
    <label for="back">Back</label>
    <input id="back" name="back">
    <button type="submit">Add card</button>
    <ul id="errors" aria-live="polite"></ul>
  </form>
  <h2>Cards</h2>
  <ul id="cards"></ul>
  <button id="study" type="button">Study</button>
  <section id="study-panel" aria-live="polite"></section>
  <p id="score"></p>
</main>

The data module. Nothing in it touches the page or localStorage:

flashcards/cards.ts
/** One flashcard, and how often it has been answered right and wrong. */
export type Card = {
  id: number;
  front: string;
  back: string;
  right: number;
  wrong: number;
};

/** What the person types to make a card. */
export type CardInput = {
  front: string;
  back: string;
};

/** Where study mode is: which card, and whether its answer is showing. */
export type Study = {
  position: number;
  showingAnswer: boolean;
};

/** Everything the page shows. Only cards is saved. */
export type AppState = {
  cards: Card[];
  study: Study | null;
  errors: string[];
};

/** A value, or every reason there is no value. */
export type Result<T> = { ok: true; value: T } | { ok: false; errors: string[] };

/** The most characters one side of a card may have. */
export const MAX_LENGTH = 80;

/** Trims both sides of a new card and checks them, reporting every problem at once. */
export function parseCardInput(front: string, back: string): Result<CardInput> {
  const input = { front: front.trim(), back: back.trim() };
  const errors: string[] = [];
  if (input.front === "") {
    errors.push("Write a question on the front.");
  }
  if (input.back === "") {
    errors.push("Write an answer on the back.");
  }
  if (input.front.length > MAX_LENGTH || input.back.length > MAX_LENGTH) {
    errors.push(`Keep each side to ${MAX_LENGTH} characters or fewer.`);
  }
  if (errors.length > 0) {
    return { ok: false, errors };
  }
  return { ok: true, value: input };
}

/** One more than the biggest id in the deck, or 1 for an empty deck. */
export function nextId(cards: Card[]): number {
  return cards.reduce((biggest, card) => Math.max(biggest, card.id), 0) + 1;
}

/** A new deck with a new card at the end. */
export function addCard(cards: Card[], input: CardInput): Card[] {
  const card: Card = { id: nextId(cards), front: input.front, back: input.back, right: 0, wrong: 0 };
  return [...cards, card];
}

/** A new deck without the card that has this id. */
export function removeCard(cards: Card[], id: number): Card[] {
  return cards.filter((card) => card.id !== id);
}

/** A new deck in which the card with this id has one more right or wrong answer. */
export function recordAnswer(cards: Card[], id: number, gotIt: boolean): Card[] {
  return cards.map((card) => {
    if (card.id !== id) {
      return card;
    }
    return gotIt ? { ...card, right: card.right + 1 } : { ...card, wrong: card.wrong + 1 };
  });
}

/** The next card to study, or null when the round has reached the end of the deck. */
export function nextStudy(study: Study, cardCount: number): Study | null {
  const position = study.position + 1;
  return position < cardCount ? { position, showingAnswer: false } : null;
}

/** Total right and wrong answers, and the percent right (0 before any answers). */
export function score(cards: Card[]): { right: number; wrong: number; percent: number } {
  const right = cards.reduce((sum, card) => sum + card.right, 0);
  const wrong = cards.reduce((sum, card) => sum + card.wrong, 0);
  const total = right + wrong;
  const percent = total === 0 ? 0 : Math.round((right / total) * 100);
  return { right, wrong, percent };
}

/** True when value has every property a Card needs, each with the right type. */
export function isCard(value: unknown): value is Card {
  return (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    typeof value.id === "number" &&
    "front" in value &&
    typeof value.front === "string" &&
    "back" in value &&
    typeof value.back === "string" &&
    "right" in value &&
    typeof value.right === "number" &&
    "wrong" in value &&
    typeof value.wrong === "number"
  );
}

/** True when value is an array of cards. */
export function isCardList(value: unknown): value is Card[] {
  return Array.isArray(value) && value.every(isCard);
}

The storage module is the one shown in 24.3. The rendering module:

flashcards/render.ts
import { score } from "./cards.ts";
import type { Card, Study } from "./cards.ts";

/** Shows one <li> per card, each with its own Delete button. */
export function renderCards(list: HTMLUListElement, cards: Card[]): void {
  list.textContent = "";
  for (const card of cards) {
    const item = document.createElement("li");
    const text = document.createElement("span");
    text.textContent = `${card.front} → ${card.back}`;
    const remove = document.createElement("button");
    remove.type = "button";
    remove.textContent = "Delete";
    remove.setAttribute("data-id", String(card.id));
    remove.setAttribute("aria-label", `Delete ${card.front}`);
    item.append(text, remove);
    list.append(item);
  }
}

/** Shows one <li> per error message, or nothing when there are none. */
export function renderErrors(list: HTMLUListElement, errors: string[]): void {
  list.textContent = "";
  for (const error of errors) {
    const item = document.createElement("li");
    item.textContent = error;
    list.append(item);
  }
}

/** A button that says label and names its job in a data-action attribute. */
function makeButton(label: string, action: string): HTMLButtonElement {
  const button = document.createElement("button");
  button.type = "button";
  button.textContent = label;
  button.setAttribute("data-action", action);
  return button;
}

/** Shows the card being studied, or nothing when study mode is off. */
export function renderStudy(panel: HTMLElement, cards: Card[], study: Study | null): void {
  panel.textContent = "";
  if (study === null) {
    return;
  }
  const card = cards[study.position];
  if (card === undefined) {
    return;
  }
  const heading = document.createElement("h2");
  heading.textContent = `Card ${study.position + 1} of ${cards.length}`;
  const front = document.createElement("p");
  front.textContent = card.front;
  panel.append(heading, front);
  if (!study.showingAnswer) {
    panel.append(makeButton("Show answer", "show"));
    return;
  }
  const back = document.createElement("p");
  back.textContent = card.back;
  panel.append(back, makeButton("Got it", "right"), makeButton("Missed it", "wrong"));
}

/** Shows the running score, or a prompt before the first answer. */
export function renderScore(line: HTMLElement, cards: Card[]): void {
  const result = score(cards);
  if (result.right + result.wrong === 0) {
    line.textContent = "No answers yet.";
    return;
  }
  line.textContent = `Score: ${result.right} right, ${result.wrong} wrong (${result.percent}%)`;
}

And main.ts, which finds the elements, holds the state, and connects each event to a data function and a render:

flashcards/main.ts
import { addCard, nextStudy, parseCardInput, recordAnswer, removeCard } from "./cards.ts";
import type { AppState } from "./cards.ts";
import { renderCards, renderErrors, renderScore, renderStudy } from "./render.ts";
import { loadCards, loadStarter, saveCards } from "./storage.ts";

/** The element that matches selector, or a clear error if the page has none. */
function find<T extends Element>(selector: string): T {
  const element = document.querySelector<T>(selector);
  if (element === null) {
    throw new Error(`The page has no ${selector} element.`);
  }
  return element;
}

const form = find<HTMLFormElement>("#card-form");
const frontInput = find<HTMLInputElement>("#front");
const backInput = find<HTMLInputElement>("#back");
const errorList = find<HTMLUListElement>("#errors");
const cardList = find<HTMLUListElement>("#cards");
const studyButton = find<HTMLButtonElement>("#study");
const studyPanel = find<HTMLElement>("#study-panel");
const scoreLine = find<HTMLParagraphElement>("#score");

const state: AppState = { cards: [], study: null, errors: [] };

function render(): void {
  renderErrors(errorList, state.errors);
  renderCards(cardList, state.cards);
  renderStudy(studyPanel, state.cards, state.study);
  renderScore(scoreLine, state.cards);
  studyButton.disabled = state.cards.length === 0;
}

function saveAndRender(): void {
  saveCards(state.cards);
  render();
}

/** Moves keyboard focus to the study panel's first button, or back to Study when the panel is empty. */
function focusStudy(): void {
  const button = studyPanel.querySelector("button");
  if (button === null) {
    studyButton.focus();
  } else {
    button.focus();
  }
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const result = parseCardInput(frontInput.value, backInput.value);
  if (!result.ok) {
    state.errors = result.errors;
    render();
    return;
  }
  state.cards = addCard(state.cards, result.value);
  state.errors = [];
  frontInput.value = "";
  backInput.value = "";
  frontInput.focus();
  saveAndRender();
});

cardList.addEventListener("click", (event) => {
  const target = event.target;
  if (!(target instanceof HTMLButtonElement)) {
    return;
  }
  state.cards = removeCard(state.cards, Number(target.getAttribute("data-id")));
  state.study = null;
  saveAndRender();
});

studyButton.addEventListener("click", () => {
  state.study = { position: 0, showingAnswer: false };
  render();
  focusStudy();
});

studyPanel.addEventListener("click", (event) => {
  const target = event.target;
  const study = state.study;
  if (!(target instanceof HTMLButtonElement) || study === null) {
    return;
  }
  const action = target.getAttribute("data-action");
  if (action === "show") {
    state.study = { position: study.position, showingAnswer: true };
  } else {
    const card = state.cards[study.position];
    state.cards = recordAnswer(state.cards, card.id, action === "right");
    state.study = nextStudy(study, state.cards.length);
  }
  saveAndRender();
  focusStudy();
});

async function start(): Promise<void> {
  state.cards = loadCards() ?? (await loadStarter());
  saveAndRender();
}

start();
Lines What they do Milestone
1–4 Imports from the three modules; the type with import type 23.6
6–22 find and every element the app uses 23.6
24 The state starts empty; start() fills it 24.3
26–32 render() draws everything from the state and switches Study off for an empty deck 24.5
34–37 saveAndRender() for every change to the deck 24.3
39–47 focusStudy() puts keyboard focus back after the panel is redrawn 24.5
49–63 Submit: validate, then either show the errors or add the card 24.2
65–73 One delegated listener for every Delete button 24.4
75–97 Study: start a round, then show, right and wrong through one delegated listener 24.5
99–104 Load the saved deck, or the starter deck, then draw 24.3
  • Every listener changes the state and then calls render() or saveAndRender(). None of them changes the page directly, so the page always matches the state.
  • Line 91 reads state.cards[study.position] without checking for undefined. The checker allows it, because indexing a Card[] gives a Card. It is safe only because every path that could shrink the deck also ends the round (line 71) and nextStudy ends it after the last card. Day 25 looks at what happens when that kind of promise breaks.
Wrap-up · 2 of 3

Go further

Day 24 has no new reading. If a milestone sent you back to an earlier day, the matching reference pages are a good second explanation: MDN: Using the Web Storage API and the Vitest expect reference.

Wrap-up · 3 of 3

Reflection

Check each statement. If the answer is “not yet,” reread the linked milestone. Then write two lines in your notes: what did you not finish today, and what is the first thing you will fix on Day 25?

  • I can order features so that the ones others depend on are built first. Reread
  • I can validate form input with a function that returns a result union, and show every error. Reread
  • I can load saved data through a type guard and fall back cleanly when it is missing or broken. Reread
  • I can handle many buttons with one delegated listener and a data attribute. Reread
  • I can keep a mode in the app state and render the page from it. Reread
  • I can write tests for an app’s core logic, including edge cases and broken data. Reread