Problems › TypeScript › orders
Work out the shipping charge
The carrier bills in weight bands, and anything over five kilos is charged per extra kilo started.
- Up to 500 g costs 3000. Up to 2 kg, 5000. Up to 5 kg, 8000.
- Above 5 kg it is 8000 plus 1500 for every extra kilo begun — 5100 g pays for one extra kilo, 6001 g pays for two.
- Express doubles whatever the total came to.
- Zero or negative weight costs nothing, express or not.
shippingCost(grams: int, express: bool) → int
Where you start
function shippingCost(grams: number, express: boolean): number {
}
Worked examples
| Call | Result |
|---|---|
shippingCost(400, false) | 3000 |
shippingCost(500, false) | 3000 |
shippingCost(1500, false) | 5000 |
shippingCost(5000, false) | 8000 |
Hint
For the top band, round the excess up to whole kilos: (excess + 999) / 1000 in integer arithmetic.
Reference solution in TypeScript
function shippingCost(grams: number, express: boolean): number {
if (grams <= 0) return 0;
let cost: number;
if (grams <= 500) cost = 3000;
else if (grams <= 2000) cost = 5000;
else if (grams <= 5000) cost = 8000;
else cost = 8000 + Math.ceil((grams - 5000) / 1000) * 1500;
return express ? cost * 2 : cost;
}