Challenge
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Battle Preparation
The game loads a Codémon from a save file, but the file is incomplete. Fill in the blanks and get it ready to fight.
Step 1: destructure `saved` into `name`, `type` and `level`, with `type` falling back to `"normal"` and `level` falling back to `1`. Step 2: print `"Loaded: name (type) Lv.X"`. Step 3: build `ready`, a new object made of every property of `saved`, plus `hp` worth 50 and `status` worth `"ok"`. Step 4: print `"Ready: X HP, status Y"` from `ready`, then `"Save untouched: X"` with the number of keys the original still has, using `Object.keys(saved).length`.
Expected output:
Loaded: Zap (normal) Lv.1
Ready: 50 HP, status ok
Save untouched: 1const saved = { name: "Zap" };
// Write your code hereExercise 2 — Tournament Registration
Trainers register any number of Codémon at once. Build the registration desk.
Step 1: `register(trainer, ...names)` receives a trainer name, then any number of Codémon names. Step 2: it prints `"trainer registers N Codémon"`, then one line per Codémon with `"- "` in front. Step 3: it returns a new array made of `roster` plus all the registered names, without modifying `roster`. Step 4: register Sam with three Codémon, store the returned array in `updated`, then print `"Roster: N"` and `"Updated: N"` with both lengths.
Expected output:
Sam registers 3 Codémon
- Aquachu
- Zap
- Metachu
Roster: 1
Updated: 4const roster = ["Pyrochu"];
// Write your function here
// Use it hereExercise 3 — Immutable Battle Turn
Play a battle turn without ever modifying the Codémon you receive. Each function returns a new object.
Step 1: `takeDamage(cdm, amount)` returns a new object with every property kept, and `hp` lowered by the amount, never below 0. Step 2: `heal(cdm, amount)` returns a new object with `hp` raised by the amount. Step 3: apply 30 damage to `zap`, then heal the result by 10, storing each step in its own constant. Step 4: print the HP after each step, then the original's HP to prove it never changed.
Expected output:
After damage: 15 HP (electric)
After heal: 25 HP
Original: 45 HPconst zap = { name: "Zap", type: "electric", hp: 45 };
// Write your functions here
// Play the turn here