Lesson 14 of 34 · Functions
JavaScript Functions Boss: The Hexweaver
Morgath the Hexweaver blocks the way. Every test you pass deals damage — pass them all to defeat it and claim a loot chest.
Morgath the Hexweaver spins curses out of pure functions: her spells fire exactly once, chain into each other and drain your mana with every cast. To break her web, you'll have to weave the same magic yourself.
Battle plan
This fight is all about functions that create, receive and remember other functions:
- Higher-order functions: all three of your functions take or return functions.
- Closures:
onceandmakeHexCountermust remember state between calls. Store that state in the outer function, not inside the function you return. - Default parameters:
makeHexCounterallows three casts unless told otherwise. - Arrow functions and template literals keep everything short and readable.
Start with chain, the shortest one, then tackle once and makeHexCounter. Test each function with console.log as you go. Remember that a function you return is a value. Store it in a variable, then call it.
Assignment
Write three functions:
-
once(fn)returns a new function that takes one argument. The first time it's called, it callsfnwith that argument and returnsfn's result. Every later call returns that same first result without callingfnagain.const summon = once((name) => `${name} appears!`); summon("Imp"); // "Imp appears!" summon("Demon"); // "Imp appears!" (fn is not called again) -
chain(first, second)returns a new function that takes a value, passes it throughfirst, then passes that result throughsecond, and returns the final result. In other words,chain(f, g)(x)equalsg(f(x)).const curse = chain((n) => n * 2, (n) => n + 1); curse(5); // 11 -
makeHexCounter(limit)returns a functioncast(spellName)that allows at mostlimitcasts.limitdefaults to3. Each allowed cast returns"<spellName> cast (<number>/<limit>)". Once the limit is used up, every further call returns"Out of mana". Each hex counter tracks its own casts.const cast = makeHexCounter(); cast("Firebolt"); // "Firebolt cast (1/3)" cast("Frost"); // "Frost cast (2/3)" cast("Shock"); // "Shock cast (3/3)" cast("Firebolt"); // "Out of mana"
Premium lesson
Unlock the full Learn JavaScript course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.
Lesson last updated on .