Problems › TypeScript › logistics
Cost of a planned route
A route is a list of legs; each leg has a distance and a per-kilometre rate. Sum the cost of the whole route.
- A leg contributes distance × rate.
- An empty route costs zero.
routeCost(legs: list<Leg>) → int
Where you start
function routeCost(legs: Leg[]): number {
}
Worked examples
| Call | Result |
|---|---|
routeCost([{"distance":10,"rate":5},{"distance":4,"rate":8}]) | 82 |
routeCost([{"distance":1,"rate":1000}]) | 1000 |
routeCost([]) | 0 |
routeCost([{"distance":0,"rate":500}]) | 0 |
Hint
Multiply per leg and add.
Reference solution in TypeScript
function routeCost(legs: Leg[]): number {
let total = 0;
for (const leg of legs) total += leg.distance * leg.rate;
return total;
}