The full text of this chapter, to read or revisit. To practise, do the exercises.
Exercise 1 — Damage Calculator 2.0
Rebuild a damage system with arrow functions and default parameters.
Step 1: `baseDamage(level, power = 10)` is an arrow function that returns `level * power`.
Step 2: `applyBonus(damage, bonus = 0)` is an arrow function that returns the damage plus the bonus.
Step 3: `report(name, damage)` prints `"name deals X damage"`.
Step 4: Zap is level 5. Report a plain attack (default power, no bonus), then a power 20 attack with a bonus of 15.
Zap deals 50 damage
Zap deals 115 damage
Starter code
// Write your functions here
// Use them here
Exercise 2 — Build Your Own filter
Write a generic function that keeps only the elements a callback approves, then use it with inline anonymous functions.
Step 1: `keep(list, test)` returns a new array containing only the elements for which `test(element)` returns `true`. The original array must not change.
Step 2: use it to keep the levels of 10 or more, and print `"High levels: N"` with how many there are.
Step 3: use it to keep the names longer than 3 characters, and print each of them on its own line.
Step 4: print `"Original still has N"` with the length of `levels`, to prove it wasn't modified.
High levels: 2
Aquachu
Metachu
Original still has 4
Starter code
const levels = [4, 12, 9, 15];
const names = ["Aquachu", "Zap", "Metachu"];
// Write your code here
Exercise 3 — Battle Events
A battle announces events. Other code registers callbacks to react to them. Build the mechanism.
Step 1: the `battle` object has a `listeners` array (empty at first) and two methods. `onHit(callback)` adds the callback to `listeners`. `hit(attacker, damage)` calls every listener with the attacker's name and the damage.
Step 2: register a first listener that prints `"attacker hits for X!"`.
Step 3: register a second listener that adds the damage to `totalDamage`.
Step 4: make Pyrochu hit for 30, then Zap for 25, then print `"Total: N"`.
Pyrochu hits for 30!
Zap hits for 25!
Total: 55
Starter code
let totalDamage = 0;
const battle = {
listeners: [],
// Write the two methods here
};
// Register the listeners and play the hits here