Full-Stack course / JavaScript fundamentals
Shipping fee
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-01-shipping-fee
cd 02-01-shipping-fee
gonomicon submitShipping fee
Goal: write a function that turns a parcel's weight into the fee a shop charges, and gives the fee back to whoever called it.
Worked example
shippingFee(weightKg) takes the weight in kilograms and returns the fee as a number.
| Weight (kg) | Fee returned |
|---|---|
0.4 | 5 |
3 | 12 |
12.5 | 30 |
31 | 50 |
0 | 0 |
The price bands
| Weight | Fee |
|---|---|
| 0 or less (nothing to ship) | 0 |
| more than 0, up to and including 1 kg | 5 |
| more than 1, up to and including 5 kg | 12 |
| more than 5, up to and including 20 kg | 30 |
| more than 20 kg | 50 |
A parcel of exactly 1 kg, 5 kg or 20 kg lands in the lower band.
Rules
- Write a function declaration called
shippingFeethat takes one parameter,weightKg. - It must
returnthe fee as a number. Don't print it: the code that calls your function needs the value back. - The tests call your function many times with different weights, so it must not remember anything between calls.
- You can try it yourself by adding
console.log(shippingFee(3));at the bottom while you work, then removing it, and runningnode shipping_fee.js.
What you'll practice
- Writing a function declaration with a parameter
- Returning a value instead of printing it
- Choosing between several outcomes with
ifandelse if - Getting a boundary right with
<=versus<
Run it
gonomicon fetch fs-week-2/02-01-shipping-fee
cd 02-01-shipping-fee
gonomicon test
gonomicon submit
Hints
- Start with the function shell:
function shippingFee(weightKg) { ... }. Inside, check the bands one after another withifandelse if, andreturna number from each one. - Check the heaviest or the lightest band first, and let each
else ifhandle the next one up. Remember that a weight of exactly 1, 5 or 20 belongs to the lower band, so use<=, not<. - Shape:
if (weightKg <= 0) { return 0; } else if (weightKg <= 1) { return 5; } else if ...and finish withreturn 50;for everything heavier than 20.