Lesson 8 of 34 · Fundamentals
JavaScript Fundamentals Boss: The Bridge Troll
Grumblebeard the Bridge Troll blocks the way. Every test you pass deals damage — pass them all to defeat it and claim a loot chest.
Grumblebeard the Bridge Troll has guarded the only bridge into Scriptoria for three hundred years. He charges a toll that depends on your level, and he never lets anyone pass who can't keep up with his favourite counting chant.
Battle plan
This fight uses everything from Chapter 1:
- Math to work out the toll, including rounding down with
Math.floor. - Comparisons and
if/elseto apply the troll's discount rule. - Functions calling functions: once
tollForworks,canCrosscan simply use it. - Loops and strings to build the chant one word at a time.
Build one function at a time and use console.log to check each one before moving on. Every test you pass is a blow against the troll.
The trickiest part is the spacing in the chant: words are separated by single spaces, with no space at the start or end. There are several ways to get this right. You could add a space before every word except the first, or build the whole string and clean it up with trim().
Assignment
Write three functions:
tollFor(level)returns the toll in gold for a hero of the given level. The toll is10 + level * 5. Heroes of level 20 or higher pay only half, rounded down.tollFor(1)→15,tollFor(10)→60,tollFor(20)→55,tollFor(25)→67
canCross(level, gold)returnstrueif a hero with that much gold can pay the toll for their level, otherwisefalse. Having exactly enough gold is fine.canCross(1, 15)→true,canCross(10, 59)→false
trollChant(n)returns the troll's chant for the numbers from 1 ton, separated by single spaces:- multiples of 3 are replaced by
"Grum" - multiples of 5 are replaced by
"Ble" - multiples of both 3 and 5 are replaced by
"GrumBle" trollChant(5)→"1 2 Grum 4 Ble"trollChant(0)→""
- multiples of 3 are replaced by
Keep learning
Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.
Lesson last updated on .