Challenge

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — Save and Reload

Simulate a full save-and-reload cycle, and prove the reloaded team is a real, independent copy.

Step 1: `saveTeam(team)` returns the compact JSON text of the team, and prints `"Saved N bytes"` with the text's length. Step 2: `loadTeam(text)` parses the text and returns the array. Step 3: save `team`, then load the text into `reloaded`. Print one line per reloaded member as `"name Lv.X"`. Step 4: raise the first reloaded member's level by 10, then print `"Original: X"` and `"Reloaded: X"` with the two first-member levels, to show they are independent.

Expected output:

Saved 56 bytes Zap Lv.4 Aquachu Lv.12 Original: 4 Reloaded: 14
Starter code
const team = [ { name: "Zap", level: 4 }, { name: "Aquachu", level: 12 } ]; // Write your functions here // Use them here

Exercise 2 — Codédex Sync

The server sends the Codédex as a list of JSON pages, one string per page. Some pages are corrupted. Merge every valid page into one list.

Step 1: `readPage(text)` parses the text and returns its `entries` array, or an empty array when the text is invalid. Use a `try...catch` inside. Step 2: build `all` by reading every page in `pages` and gathering the entries into one flat array. Step 3: print `"Entries: N"`, then the names sorted alphabetically and joined with `", "`. Step 4: print `"Corrupted pages: N"` with how many pages returned nothing.

Expected output:

Entries: 4 Aquachu, Metachu, Pyrochu, Zap Corrupted pages: 1
Starter code
const pages = [ '{"entries":[{"name":"Zap"},{"name":"Aquachu"}]}', '{"entries":[{"name":"Metachu"}', '{"entries":[{"name":"Pyrochu"},{"name":"Metachu"}]}' ]; // Write your function here // Merge the pages here

Exercise 3 — Battle Report Exporter

After a battle, the game builds a report object, exports it as JSON for the server, and reads the server's acknowledgement back.

Step 1: build `report`, an object with `winner` set to the name of the fighter with the highest `hp`, `turns` set to 3, and `survivors` set to the names of every fighter with HP above 0. Step 2: print the report as compact JSON. Step 3: `ack` is the server's answer as text. Parse it inside a `try`; if `accepted` is `true` print `"Report accepted, id X"` using its `id`, otherwise print `"Report rejected"`. On invalid text print `"Bad acknowledgement"`. Step 4: run step 3 on both answers in `acks`.

Expected output:

{"winner":"Metachu","turns":3,"survivors":["Zap","Metachu"]} Report accepted, id 77 Bad acknowledgement
Starter code
const fighters = [ { name: "Zap", hp: 20 }, { name: "Pyrochu", hp: 0 }, { name: "Metachu", hp: 60 } ]; const acks = [ '{"accepted":true,"id":77}', 'not json at all' ]; // Write your code here
Back to the course