Challenge

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

▶ Do the exercises

Exercise 1 — Bulletproof Team Loader

Load a team from a list of raw entries, some of which are broken in different ways. Every good entry must load, every bad one must be reported by type, and the program must never crash.

Step 1: `load(entry)` throws `"Missing name"` if the entry has no `name`, and `"Bad level"` if its `level` is not between 1 and 100. Otherwise it returns `"name Lv.X"`. Step 2: loop over `entries` with a `try` per entry. Print the loaded line, or `"Skipped N: message"` with the index and the error's message. A `null` entry must be reported too, using the message JavaScript itself produces. Step 3: print `"Loaded N of M"` at the end.

Expected output:

Zap Lv.4 Skipped 1: Missing name Skipped 2: Bad level Aquachu Lv.12 Skipped 4: Cannot read properties of null (reading 'name') Loaded 2 of 5
Starter code
const entries = [ { name: "Zap", level: 4 }, { level: 8 }, { name: "Metachu", level: 250 }, { name: "Aquachu", level: 12 }, null ]; // Write your function here // Load the team here

Exercise 2 — Battle With Cleanup

Each battle turn opens a log, plays a move, and must close the log even when the move is illegal.

Step 1: `playMove(name, damage)` throws `"Illegal damage: X"` if the damage is negative or above 100. Otherwise it returns `"name deals X"`. Step 2: `turn(name, damage)` prints `"Log opened"`, then in a `try` prints the result of `playMove`. On failure it prints `"Turn cancelled: message"`. A `finally` prints `"Log closed"`. Step 3: play three turns: Zap for 30, Metachu for 150, Aquachu for -5.

Expected output:

Log opened Zap deals 30 Log closed Log opened Turn cancelled: Illegal damage: 150 Log closed Log opened Turn cancelled: Illegal damage: -5 Log closed
Starter code
// Write your functions here // Play the turns here

Exercise 3 — Error Triage

Run a batch of risky operations, classify each failure by its error type, and produce a triage report.

Step 1: `operations` is an array of functions. Some succeed, some crash with a `TypeError`, a `ReferenceError` or a `RangeError`. Step 2: call each one inside a `try`. On success print `"OK: result"`. On failure print `"type: message"` using the caught error's `name` and `message`. Step 3: count the failures per type in a Map and print `"type x N"` for each type met, in order of first appearance. Then print `"Succeeded: N"`.

Expected output:

OK: 42 TypeError: Cannot read properties of undefined (reading 'name') RangeError: Invalid count value: -1 OK: Zap TypeError: level is not a function TypeError x 2 RangeError x 1 Succeeded: 2
Starter code
const level = 5; const operations = [ () => 42, () => undefined.name, () => "#".repeat(-1), () => "Zap", () => level() ]; // Write your code here
Back to the course