Functional Weave
Code in TypeScript

fleet.fuel-cost@1.0.0

README.md

1,722 bytes · view raw

# fleet.fuel-cost

The fuel a trip burns and what it costs, from the distance, the vehicle's fuel
economy and the pump price per litre.
`fuelCost("100", "mi", "50", "mpg-uk", 1459, "GBP", "half-up")` is 9.092
litres costing 13.27.

## Inputs

- `distance` and `economy` are plain decimal text ("250", "48.7"), so a
  distance read off an odometer or a WLTP figure goes in exactly.
- `economyUnit` names the gallon. UK figures are miles per **imperial** gallon
  (4.54609 L); US figures are miles per US gallon (3.785411784 L), about 20%
  smaller. Plain `mpg` is refused because the two are easy to mix up. Or give
  litres per 100 km.
- `pricePerLitreTenths` is the price as a pump shows it, to a tenth of a
  penny: 145.9p is `1459`. A price in whole pence is just `1450` and so on.

## Exactness

The litres are an exact fraction of the inputs. The mile (1.609344 km) and both
gallons come from `units.convert`, which defines them exactly. The cost is
litres x price, rounded once to a minor unit with the mode you choose. The
litres in the result are rounded half-up to 3 places for display only: the cost
never uses them. That matters: one mile at 1 mpg (UK) and 81.5p is 370.506335p,
which is 371p; rounding the litres to 4.546 first (or using the common
approximation 4.546 L per gallon) gives 370p.

The product is held in big integers (`math.round-div-big`), so long distances
with many decimal places cannot overflow; a cost beyond 2^53 - 1 minor units is
refused because JavaScript could not represent it.

## Edges

Zero distance and a zero price cost nothing. A zero economy, a negative or
malformed number, an unknown unit, a fractional or negative price, a bad
currency code and an unknown mode are errors.