All files / applications/go-by-transit/src/view/nearby/components nearbyRouteArrivals.ts

93.33% Statements 56/60
75.34% Branches 55/73
96.29% Functions 26/27
93.1% Lines 54/58

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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204                            172x           52x 52x                       304x 292x   12x 304x       60x                         60x 60x               60x   60x 88x       88x 88x 152x 152x 152x 92x         92x     152x     16x           152x   152x                         92x         60x 10x     50x 50x                 62x                   108x 106x     2x   2x 1x   2x   2x 1x     2x   4x                     106x 106x 92x 92x 92x   106x 52x       152x         92x 152x               8x     8x 1x     7x              
import { each, filter, groupBy } from "lodash";
import { WalkingEstimate } from "../../../api/mapbox/walking";
import { Arrival, ArrivalData } from "../../../api/trimet/interfaces/arrivals";
import { Direction, StopData, StopLocation, TrimetRoute } from "../../../api/trimet/interfaces/types";
import { getDistance } from "../util/turfUtils";
 
export interface RouteStop {
  stop: StopLocation;
  arrivals: Arrival[];
  distanceMiles?: number;
  walkingEstimate?: WalkingEstimate;
}
 
function stopDistance(stop: RouteStop, walking: boolean) {
  return walking
    ? stop.walkingEstimate?.status === "ready" ? stop.walkingEstimate.meters : Infinity
    : stop.distanceMiles ?? Infinity;
}
 
function getRouteName(route: TrimetRoute): string {
  const prefix = `${route.route}-`;
  return route.desc.startsWith(prefix)
    ? route.desc.slice(prefix.length).trimStart()
    : route.desc;
}
 
export interface RouteStructure {
  key: string;
  route: TrimetRoute;
  direction: Direction;
  stops: RouteStop[];
}
export function getArrivalTime(arrival?: Arrival): number | undefined {
  if (!arrival) {
    return undefined;
  }
  const timestamp = arrival.estimated || arrival.scheduled;
  return Number.isFinite(timestamp) && timestamp > 0 ? timestamp : undefined;
}
 
function hasCurrentLocation(currentLocation: number[]): boolean {
  return Boolean(
    currentLocation?.length >= 2 &&
    Number.isFinite(currentLocation[0]) &&
    Number.isFinite(currentLocation[1])
  );
}
 
export function getRouteArrivals(
  arrivalData: ArrivalData,
  nearbyStops: StopData,
  currentLocation: number[],
  walkingEstimates?: ReadonlyMap<number, WalkingEstimate>
): RouteStructure[] {
  const arrivalsByLocation = groupBy(arrivalData?.arrival || [], "locid");
  const routeDirections = new Map<
    string,
    {
      route: TrimetRoute;
      direction: Direction;
      stops: Map<number, RouteStop>;
    }
  >();
  const locationIsAvailable = hasCurrentLocation(currentLocation);
 
  each(nearbyStops?.location || [], (stop: StopLocation) => {
    Iif (stop.locid == null) {
      return;
    }
 
    each(stop.route || [], (route: TrimetRoute) => {
      each(route.dir || [], (direction: Direction) => {
        const key = `${route.route}-${direction.dir}`;
        let routeDirection = routeDirections.get(key);
        if (!routeDirection) {
          routeDirection = {
            direction,
            route,
            stops: new Map<number, RouteStop>(),
          };
          routeDirections.set(key, routeDirection);
        }
 
        const stopArrivals = filter(
          arrivalsByLocation[stop.locid],
          (arrival: Arrival) =>
            arrival.route === route.route && arrival.dir === direction.dir
        ).sort(
          (a, b) =>
            (getArrivalTime(a) ?? Infinity) - (getArrivalTime(b) ?? Infinity)
        );
        const stopHasCoordinates =
          Number.isFinite(stop.lng) && Number.isFinite(stop.lat);
 
        routeDirection.stops.set(stop.locid, {
          arrivals: stopArrivals,
          distanceMiles:
            locationIsAvailable && stopHasCoordinates
              ? getDistance(currentLocation, [stop.lng, stop.lat])
              : undefined,
          stop,
          walkingEstimate: walkingEstimates?.get(stop.locid),
        });
      });
    });
  });
 
  return Array.from(routeDirections, ([key, routeDirection]) => ({
    direction: routeDirection.direction,
    key,
    route: routeDirection.route,
    stops: Array.from(routeDirection.stops.values()).sort((a, b) => {
      if (walkingEstimates) {
        return stopDistance(a, true) - stopDistance(b, true) ||
          Number(a.stop.locid) - Number(b.stop.locid);
      }
      Eif (a.distanceMiles != null && b.distanceMiles != null) {
        return (
          a.distanceMiles - b.distanceMiles ||
          Number(a.stop.locid) - Number(b.stop.locid)
        );
      }
      return Number(a.stop.locid) - Number(b.stop.locid);
    }),
  })).sort(
    (a, b) =>
      a.route.route - b.route.route ||
      a.direction.desc.localeCompare(b.direction.desc) ||
      a.direction.dir - b.direction.dir
  );
}
 
export function filterRouteStructures(
  routes: RouteStructure[],
  selectedValues: string[]
): RouteStructure[] {
  if (selectedValues.length === 0) {
    return routes;
  }
 
  const selectedRoutes = new Set(
    selectedValues
      .filter((value) => value.startsWith("route:"))
      .map((value) => value.slice("route:".length))
  );
  const selectedDirections = new Set(
    selectedValues
      .filter((value) => value.startsWith("direction:"))
      .map((value) => value.slice("direction:".length))
  );
 
  return routes.filter(
    (route) =>
      selectedRoutes.has(String(route.route.route)) ||
      selectedDirections.has(route.key)
  );
}
export type RouteSort = "arrival" | "distance" | "route";
 
export function getDisplayRoutes(
  filteredRoutes: RouteStructure[],
  sortBy: RouteSort,
  walkingEnabled: boolean
) {
  const groupedRoutes = new Map<number, RouteStructure[]>();
  filteredRoutes.forEach((route) => {
    const directions = groupedRoutes.get(route.route.route) || [];
    directions.push(route);
    groupedRoutes.set(route.route.route, directions);
  });
  return Array.from(groupedRoutes.values())
    .map((directions) => ({
      directions,
      distance: Math.min(
        ...directions.flatMap((direction) =>
          direction.stops.map((stop) => stopDistance(stop, walkingEnabled))
        )
      ),
      nextArrival: Math.min(
        ...directions.flatMap((direction) =>
          direction.stops.map(
            (stop) => getArrivalTime(stop.arrivals[0]) ?? Infinity
          )
        )
      ),
      route: directions[0].route,
      routeName: getRouteName(directions[0].route),
    }))
    .sort((a, b) => {
      Iif (sortBy === "route") {
        return a.route.route - b.route.route;
      }
      if (sortBy === "distance") {
        return a.distance - b.distance || a.route.route - b.route.route;
      }
 
      return (
        a.nextArrival - b.nextArrival ||
        a.distance - b.distance ||
        a.route.route - b.route.route
      );
    });
}