Course outline
Full-Stack course / JavaScript fundamentals

Shipping fee

Lab

How to fetch and submit this exercise

Once: install the tool and connect your account.

curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon login

Each 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 submit

The runner depends on the exercise: JavaScript/TypeScript/React labs run with Vitest, Python labs with pytest, and config-file labs (Docker, CI, Terraform, Nginx) are checked by parsing your file. gonomicon test runs the visible checks on your computer first; submitting also runs the hidden checks on our server.

Shipping 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.45
312
12.530
3150
00

The price bands

WeightFee
0 or less (nothing to ship)0
more than 0, up to and including 1 kg5
more than 1, up to and including 5 kg12
more than 5, up to and including 20 kg30
more than 20 kg50

A parcel of exactly 1 kg, 5 kg or 20 kg lands in the lower band.

Rules

  • Write a function declaration called shippingFee that takes one parameter, weightKg.
  • It must return the 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 running node 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 if and else 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

  1. Start with the function shell: function shippingFee(weightKg) { ... }. Inside, check the bands one after another with if and else if, and return a number from each one.
  2. Check the heaviest or the lightest band first, and let each else if handle the next one up. Remember that a weight of exactly 1, 5 or 20 belongs to the lower band, so use <=, not <.
  3. Shape: if (weightKg <= 0) { return 0; } else if (weightKg <= 1) { return 5; } else if ... and finish with return 50; for everything heavier than 20.