Challenge 3: Strings

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

▶ Do the exercises

Exercise 1 — The Battle Log

Third and last final challenge: turn the raw text log of an arena day into a clean report. This challenge combines string methods like `split()`, `trim()`, `indexOf()` and `slice()`, `parseInt()`, a custom error caught with `try...catch`, a `Map`, `sort()` and `reduce()`.

Step 1: `parseEntry(entry)` splits the entry on `|` and trims both parts. The damage is converted with `parseInt()`; if the result is `NaN`, throw an `Error` with the message `"invalid damage (text)"`. The first part has the form `"attacker uses move on target"`: find `" uses "` and `" on "` with `indexOf()`, then cut out the attacker and the move with `slice()`. Return `{ attacker, move, damage }`. Step 2: turn `rawLog` into entries: split on line breaks, trim each line and drop the empty ones. Print the header `"=== BATTLE LOG ==="`. Then, for each entry inside a `try...catch`: parse it, add its damage to the attacker's total in a `Map`, and remember the strongest hit. In `catch`, print `"Skipped entry N: message"` (N starts at 1). Step 3: print `"Strongest hit: move by attacker (damage)"`, then one line per attacker sorted from highest to lowest total: the name padded to 10 characters, the total padded to 3, a space, and one `#` per 3 damage points (rounded). Finish with `"Total: X"`, computed with `reduce()`.

Expected output:

=== BATTLE LOG === Skipped entry 5: invalid damage (eleven) Strongest hit: Flamethrower by Pyrochu (25) Zap 27 ######### Pyrochu 25 ######## Rockachu 20 ####### Aquachu 12 #### Total: 84
Starter code
// The raw log: one hit per line, "attacker uses move on target | damage" const rawLog = ` Zap uses Thunderbolt on Aquachu | 18 Aquachu uses Water Gun on Zap | 12 Pyrochu uses Flamethrower on Florachu | 25 Zap uses Quick Attack on Aquachu | 9 Pyrochu uses Ember on Florachu | eleven Rockachu uses Rock Throw on Zap | 20 `; // Step 1: parseEntry(entry) // Step 2: read the log // Step 3: print the report
Back to the course