Full-Stack course / JavaScript fundamentals
Basket summary
How to fetch and submit this exercise
Once: install the tool and connect your account.
curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon loginEach exercise: download it, edit the file named in the instructions, then submit.
gonomicon fetch fs-week-2/02-03-basket-summary
cd 02-03-basket-summary
gonomicon submitBasket summary
Goal: price a shopping basket with three functions: one with a default parameter and two that accept any number of prices through a rest parameter.
Worked example
| Call | Returns |
|---|---|
withTax(100) | 120 |
withTax(80, 25) | 100 |
withTax(50, 0) | 50 |
sumAll(5, 10, 20) | 35 |
sumAll() | 0 |
basketLine("Gifts", 10, 20, 30) | "Gifts x3 = 60" |
basketLine("Snacks") | "Snacks x0 = 0" |
basketLine() | "Basket x0 = 0" |
basketLine(undefined, 5, 10) | "Basket x2 = 15" |
The three functions
withTax(price, percent)gives back the price pluspercentpercent of the price. If nobody says what the percent is, use20.sumAll(...amounts)gives back the total of every number it was given, or0when it was given none.basketLine(label, ...prices)gives back a line of text: the label, anx, how many prices there were, an equals sign and the total of the prices. If nobody gives a label, use"Basket". Passingundefinedas the label means "I'm not giving one".
Rules
- Write all three as function declarations, with exactly these names.
withTaxmust use a default parameter.sumAllandbasketLinemust use a rest parameter, and must not use the oldargumentsobject.- Each function must
returnits answer rather than print it. - Walk the list of prices with a loop.
- You can try things out with a line like
console.log(basketLine("Gifts", 10, 20, 30));at the bottom while you work, then remove it, and runnode basket_summary.js.
What you'll practice
- A default parameter, and what it takes to trigger one
- A rest parameter collecting leftover arguments into a list
- Walking that list with
for...ofwhile keeping a running total - Building one line of text with a template literal
Run it
gonomicon fetch fs-week-2/02-03-basket-summary
cd 02-03-basket-summary
gonomicon test
gonomicon submit
Hints
- For
withTax, put the default right in the parameter list:percent = 20. For the other two, a rest parameter (...amounts,...prices) hands you every extra argument as a list you can walk withfor...of. - Inside
sumAll, make aletbox that starts at 0 and add each amount to it in afor...ofloop.basketLineneeds the same total plus a count of how many prices came in, so keep two boxes going in one loop. The label slot comes first, so give it a default and put the rest parameter after it. function withTax(price, percent = 20) { return price + price * percent / 100; }. For the other two:function sumAll(...amounts) { let total = 0; for (const amount of amounts) { total += amount; } return total; }, andbasketLineworks the same way with a counter, ending inreturn${label} x${count} = ${total};.