mobileapp / src /utils /fareCalculator.ts
Antaram Dev Bot
feat: complete ANTARAM.ORG ride-sharing app frontend
5c876be
/**
* Offline fare estimation based on distance and vehicle type.
*
* Rates (INR):
* Bike: ₹10 base + ₹8/km
* Auto: ₹20 base + ₹12/km
* Car: ₹30 base + ₹15/km
*
* The estimate returns a min/max range to account for traffic, route
* variations, and surge considerations. The buffer is configurable via
* FARE_ESTIMATE_BUFFER in constants.
*/
import type { VehicleType } from '../types/user';
import { VEHICLE_TYPES, FARE_ESTIMATE_BUFFER } from './constants';
export interface FareEstimate {
min: number;
max: number;
baseFare: number;
perKmRate: number;
total: number;
}
/**
* Calculate fare estimate for a given distance and vehicle type.
*
* @param distanceKm - Distance in kilometers
* @param vehicleType - Vehicle type (bike, auto, car)
* @returns Fare estimate with min/max range and breakdown
*/
export function estimateFare(
distanceKm: number,
vehicleType: VehicleType,
): FareEstimate {
const vehicle = VEHICLE_TYPES.find((v) => v.type === vehicleType);
if (!vehicle) {
throw new Error(`Unknown vehicle type: ${vehicleType}`);
}
if (distanceKm <= 0) {
return {
min: vehicle.baseFare,
max: vehicle.baseFare,
baseFare: vehicle.baseFare,
perKmRate: vehicle.perKmRate,
total: vehicle.baseFare,
};
}
const total = vehicle.baseFare + vehicle.perKmRate * distanceKm;
const buffer = total * FARE_ESTIMATE_BUFFER;
return {
min: Math.round(total - buffer),
max: Math.round(total + buffer),
baseFare: vehicle.baseFare,
perKmRate: vehicle.perKmRate,
total: Math.round(total),
};
}
/**
* Calculate the fare per person when sharing a ride.
*
* @param totalFare - The total fare estimate
* @param passengers - Number of passengers (minimum 1)
* @returns Per-passenger fare
*/
export function farePerPerson(totalFare: number, passengers: number): number {
const count = Math.max(1, passengers);
return Math.ceil(totalFare / count);
}
/**
* Format fare in Indian Rupees.
*
* @param amount - Amount in INR
* @returns Formatted string like "₹125"
*/
export function formatFare(amount: number): string {
return `₹${Math.round(amount)}`;
}
/**
* Format fare range.
*
* @param min - Minimum amount
* @param max - Maximum amount
* @returns Formatted string like "₹100 - ₹130"
*/
export function formatFareRange(min: number, max: number): string {
return `${formatFare(min)} - ${formatFare(max)}`;
}