Bookmark this: tool.io/cost/fuel/source-code
Fuel Cost Calculator Source Code
Browse the implementation files for Fuel Cost Calculator.tool.ts typescript
import {
CURRENCY_OPTIONS,
formatCostSummary,
formatMoney,
parseCurrency,
parseNonnegative,
parsePositive
} from '../calculation';
import { calculateFuelCost as calculatePortableFuelCost } from '@tool.io/tools/cost/fuel';
export interface FuelCostResult {
fuelAmount: number;
fuelUnit: 'gal' | 'L';
totalCost: number;
}
export const calculateFuelCost = (
systemInput: unknown,
distanceInput: unknown,
efficiencyInput: unknown,
priceInput: unknown
): FuelCostResult | null => {
if (systemInput !== 'us' && systemInput !== 'metric')
return null;
const distance = parseNonnegative(distanceInput);
const efficiency = parsePositive(efficiencyInput);
const price = parseNonnegative(priceInput);
if (
distance === null ||
efficiency === null ||
price === null
)
return null;
const result = calculatePortableFuelCost(
systemInput,
distance,
efficiency,
price,
'USD'
);
return result
? {
fuelAmount: result.fuelAmount,
fuelUnit: result.fuelUnit,
totalCost: result.totalCost
}
: null;
};
export const fuelCost = (
currencyInput: unknown,
systemInput: unknown,
distanceInput: unknown,
efficiencyInput: unknown,
priceInput: unknown
): string => {
const currency = parseCurrency(currencyInput);
const result = calculateFuelCost(
systemInput,
distanceInput,
efficiencyInput,
priceInput
);
return !currency || !result
? ''
: formatCostSummary([
[
'Fuel needed',
`${result.fuelAmount.toFixed(2)} ${result.fuelUnit}`
],
['Fuel cost', formatMoney(result.totalCost, currency)]
]);
};
export const Tool: TypeTool = {
name: 'Fuel Cost Calculator',
slug: 'cost/fuel',
intro:
'Estimate fuel consumption and cost from distance, fuel economy, and the local fuel price.',
tool: fuelCost,
i: [
{
example: 'USD',
label: 'Currency',
options: CURRENCY_OPTIONS,
placeholder: 'Select currency',
type: 'select'
},
{
example: 'us',
label: 'Units',
options: [
{
selected: true,
text: 'US — miles, MPG, price/gallon',
value: 'us'
},
{
text: 'Metric — km, L/100 km, price/liter',
value: 'metric'
}
],
placeholder: 'Select units',
type: 'select'
},
{
example: '300',
label: 'Distance',
placeholder: 'Trip distance',
type: 'number'
},
{
example: '30',
label: 'Fuel Economy',
placeholder: 'MPG or L/100 km',
type: 'number'
},
{
example: '3.50',
label: 'Fuel Price',
placeholder: 'Price per gallon or liter',
type: 'number'
}
],
o: [
{
example: 'Fuel needed: 10.00 gal\nFuel cost: $35.00',
label: 'Fuel Cost',
placeholder: 'Fuel estimate will appear here...',
render: 'textarea',
type: 'text'
}
],
alternative: [
{
title: 'Road Trip Cost Calculator',
url: '/cost/road-trip'
}
],
cite: [
{
title: 'Fuel economy in automobiles - Wikipedia',
url: 'https://en.wikipedia.org/wiki/Fuel_economy_in_automobiles'
}
]
};
export default Tool;
Description
Browse the implementation files for Fuel Cost Calculator.