flight-planner
Version:
Plan and route VFR flights
56 lines (55 loc) • 2.52 kB
JavaScript
import calculateFlightPerformance, { calculateFuelConsumption } from './aircraft';
/**
* Maps a route trip to an array of waypoints.
*
* This function extracts all waypoints from a route trip by taking the start and end
* waypoints of each leg and flattening them into a single array.
*
* @param routeTrip - The route trip containing legs with start and end waypoints
* @returns An array of waypoints representing all points in the route trip
*/
export function routeTripWaypoints(routeTrip) {
return routeTrip.route.flatMap(leg => [leg.start, leg.end]);
}
/**
* Plans a route between the given waypoints.
*
* @param waypoints - An array of waypoints.
* @param aircraft - An optional aircraft object.
* @returns A route trip object.
*/
export function planFlightRoute(waypoints, options) {
const aircraft = options?.aircraft;
const legs = waypoints.slice(0, -1).map((startWaypoint, i) => {
const endWaypoint = waypoints[i + 1];
const distance = startWaypoint.getDistanceTo(endWaypoint);
const trueTrack = startWaypoint.getHeadingTo(endWaypoint);
const metarData = startWaypoint.metarStation?.metarData;
const wind = { direction: metarData?.windDirection || 0, speed: metarData?.windSpeed || 0 };
return {
start: startWaypoint,
end: endWaypoint,
distance: distance,
trueTrack: trueTrack,
windDirection: wind.direction,
windSpeed: wind.speed,
performance: aircraft ? calculateFlightPerformance(aircraft, distance, trueTrack, wind) : undefined,
};
});
const totalDistance = legs.reduce((acc, leg) => acc + leg.distance, 0);
const totalDuration = legs.reduce((acc, leg) => acc + (leg.performance?.duration || 0), 0);
const totalFuelConsumption = legs.reduce((acc, leg) => acc + (leg.performance?.fuelConsumption || 0), 0);
const reserveFuel = options?.reserveFuel ?? (aircraft ? calculateFuelConsumption(aircraft, 30) : 0);
const totalFuelRequired = totalFuelConsumption + (reserveFuel || 0);
const departureDate = options?.departureDate || new Date();
const arrivalDate = new Date(departureDate.getTime() + totalDuration * 60 * 1000);
return {
route: legs,
totalDistance: totalDistance,
totalDuration: totalDuration,
totalFuelConsumption: totalFuelConsumption,
totalFuelRequired: totalFuelRequired,
departureDate: departureDate,
arrivalDate: arrivalDate,
};
}