All files / src/hooks useNearbyBuildings.ts

60% Statements 12/20
40% Branches 6/15
100% Functions 2/2
60% Lines 12/20

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                          29x   1x 1x   1x               1x 1x   1x       1x 1x 1x   1x                         29x    
import { useCallback } from "react";
import useLocationStore from "./useLocationStore";
import { findNearestBuilding, isOnCampus } from "../utils/locationUtils";
import { BUILDINGS } from "../data/buildings";
 
type LocationStoreState = ReturnType<typeof useLocationStore.getState>;
 
export type NearbyBuildingUpdatesGetter = (
  prev: LocationStoreState,
  coords: { latitude: number; longitude: number },
) => Record<string, unknown>;
 
export default function useNearbyBuildings() {
  const getNearbyBuildingUpdates: NearbyBuildingUpdatesGetter = useCallback(
    (prev, coords) => {
      const updates: Record<string, unknown> = {};
      const campusInfo = isOnCampus(coords);
 
      Iif (!campusInfo.onCampus) {
        if (prev.nearestBuilding !== null) {
          updates.nearestBuilding = null;
          updates.nearestBuildingDistance = null;
        }
        return updates;
      }
 
      const nearest = findNearestBuilding(coords, BUILDINGS);
      Eif (nearest && nearest.distance < 200) {
        const shouldUpdateNearest =
          prev.nearestBuilding?.id !== nearest.building.id ||
          prev.nearestBuildingDistance === null ||
          Math.abs(prev.nearestBuildingDistance - nearest.distance) > 1;
 
        Eif (shouldUpdateNearest) {
          updates.nearestBuilding = nearest.building;
          updates.nearestBuildingDistance = nearest.distance;
        }
        return updates;
      }
 
      if (prev.nearestBuilding !== null) {
        updates.nearestBuilding = null;
        updates.nearestBuildingDistance = null;
      }
 
      return updates;
    },
    [],
  );
 
  return { getNearbyBuildingUpdates };
}