Code: Select all
interface Order {
id: number;
pickup: Location;
delivery: Location;
}
interface Location {
id: number;
latitude: number;
longitude: number;
}
// Function to calculate distance using the Haversine formula
function getDistance(loc1: Location, loc2: Location): number {
/** Implementation not important here **/
}
function getSortedUniqueLocations(orderArray: Order[]): Location[] {
if (orderArray.length === 0) return [];
const uniqueLocations = new Map();
for (let i = 0; i < orderArray.length; i++) {
const order = orderArray[i];
const pickup = order.pickup;
const delivery = order.delivery;
const pickupKey = `${pickup.latitude},${pickup.longitude}`;
const deliveryKey = `${delivery.latitude},${delivery.longitude}`;
if (!uniqueLocations.has(pickupKey)) {
uniqueLocations.set(pickupKey, pickup);
}
if (!uniqueLocations.has(deliveryKey)) {
uniqueLocations.set(deliveryKey, delivery);
}
}
const locations = Array.from(uniqueLocations.values());
const firstLocation = orderArray[0].pickup;
locations.sort((a, b) => getDistance(firstLocation, a) - getDistance(firstLocation, b));
return locations;
}