Challenge

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

▶ Do the exercises

Exercise 1 — Private Codédex

Build a Codédex whose entries cannot be modified from outside. Only the functions you provide may touch the list.

Step 1: `makeCodedex()` keeps a hidden array `entries` and returns an object with three methods. Step 2: `add(name)` adds the name only if it isn't there yet, printing `"Added X"`, otherwise it prints `"Already known: X"`. Step 3: `count()` returns how many entries there are, and `list()` returns the names joined with `", "`. Step 4: add Zap, Aquachu, then Zap again. Print the count, the list, and the result of reading `entries` directly on the object.

Expected output:

Added Zap Added Aquachu Already known: Zap Count: 2 Zap, Aquachu Direct access: undefined
Starter code
// Write your factory here // Use it here

Exercise 2 — Independent Battle Timers

Two arenas run at the same time, each counting its own turns. Neither may ever see the other's count.

Step 1: `makeArena(name)` keeps a hidden `turns` starting at 0 and returns a function. Step 2: the returned function increases the count and returns `"name - turn N"`. Step 3: build an arena called `"Rock"` and one called `"Water"`. Step 4: play two turns in Rock, one in Water, then one more in Rock, printing each result. The counts must stay separate.

Expected output:

Rock - turn 1 Rock - turn 2 Water - turn 1 Rock - turn 3
Starter code
// Write your factory here // Use it here

Exercise 3 — Damage Calculator Factory

Each Codémon type hits differently. Build one factory that produces a specialised damage calculator per type, each remembering its own multiplier.

Step 1: `makeCalculator(type, multiplier)` returns a function taking a base damage. Step 2: that function declares a local `total` equal to the base times the multiplier, then returns `"type hits for X"`. Step 3: build a fire calculator with multiplier 2 and a water one with multiplier 3. Step 4: print the result of each one on a base of 20, then on a base of 50, to show each remembers its own setting.

Expected output:

fire hits for 40 water hits for 60 fire hits for 100 water hits for 150
Starter code
// Write your factory here // Use it here
Back to the course