All files / applications/go-by-transit/src/state/arrivals formatStopLocations.ts

100% Statements 8/8
75% Branches 3/4
100% Functions 5/5
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53                                    19x   19x             19x 19x                         19x         19x 19x   19x      
import { getDistance } from "geolib";
import { map, mapKeys } from "lodash";
import { Coords, StopLocation } from "../../api/trimet/interfaces/types";
 
export interface StopLocationsDictionary {
  [locationId: number]: StopLocationWithDistance;
}
 
export interface StopLocationWithDistance extends StopLocation {
  distance: number;
  distanceOrder: number;
}
 
function calculateDistance(
  lng: number,
  lat: number,
  currentLocation: Coords,
): number {
  const stopLocation = { latitude: lat, longitude: lng };
 
  return getDistance(stopLocation, currentLocation);
}
 
function addDistanceToCurrentLocation(
  stopLocation: StopLocation[],
  currentLocation: Coords,
): StopLocationWithDistance[] {
  return map(stopLocation, (location: StopLocation, index) => {
    return {
      ...location,
      route: location.route ?? [],
      distance: calculateDistance(location.lng, location.lat, currentLocation),
      distanceOrder: index,
    };
  });
}
 
export default function formatStopLocations(
  stopLocation: StopLocation[],
  currentLocation: Coords,
): StopLocationsDictionary {
  const stopLocationsWithDistance = addDistanceToCurrentLocation(
    stopLocation,
    currentLocation,
  );
 
  return mapKeys(stopLocationsWithDistance, (location) => {
    const id = location.locid ? location.locid : location.id;
 
    return id;
  });
}