From 302ed1e11e8aa5ac76f0b5e52f8ea76022e6b484 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Adrian=20Or=C5=82=C3=B3w?= <adrian.orlow@fishbrain.com>
Date: Tue, 17 Oct 2023 23:17:55 +0200
Subject: [PATCH] feat(map): improve readability of point to lat lng util

---
 src/utils/map/pointToLatLng.ts | 33 +++++++++++++++++++--------------
 1 file changed, 19 insertions(+), 14 deletions(-)

diff --git a/src/utils/map/pointToLatLng.ts b/src/utils/map/pointToLatLng.ts
index 396f0ef8..d6d82a4e 100644
--- a/src/utils/map/pointToLatLng.ts
+++ b/src/utils/map/pointToLatLng.ts
@@ -3,28 +3,33 @@ import { LATLNG_FALLBACK, VALID_MAP_SIZE_SCHEMA } from '@/constants/map';
 import { MapSize } from '@/redux/map/map.types';
 import { LatLng, Point } from '@/types/map';
 import { radiansToDegrees } from '../number/radiansToDegrees';
-import { getPointOriginAndShifted } from './getPointOriginAndShifted';
+import { getPointOffset } from './getPointOffset';
 
-export const pointToLatLng = (point: Point, mapSize?: MapSize): LatLng => {
-  if (!mapSize) {
-    return LATLNG_FALLBACK;
-  }
+const FULL_CIRCLE_DEGREES = 360;
 
-  try {
-    VALID_MAP_SIZE_SCHEMA.parse(mapSize);
-  } catch (e) {
+const getIsMapSizeValid = (mapSize?: MapSize): boolean => {
+  const parseResult = VALID_MAP_SIZE_SCHEMA.safeParse(mapSize);
+
+  if (parseResult.success === false) {
     // TODO: need to rething way of handling parsing errors, for now let's leave it to console.log
     // eslint-disable-next-line no-console
-    console.error('Error parsing map size', e);
+    console.error('Error parsing map size', parseResult.error);
+  }
+
+  return parseResult.success;
+};
+
+export const pointToLatLng = (point: Point, mapSize?: MapSize): LatLng => {
+  const isMapSizeValid = getIsMapSizeValid(mapSize);
+  if (!isMapSizeValid || !mapSize) {
     return LATLNG_FALLBACK;
   }
 
-  const { pointOrigin, pointShifted } = getPointOriginAndShifted(point, mapSize);
-  const pixelsPerLonDegree = mapSize.tileSize / 360;
+  const { x: xOffset, y: yOffset } = getPointOffset(point, mapSize);
+  const pixelsPerLonDegree = mapSize.tileSize / FULL_CIRCLE_DEGREES;
   const pixelsPerLonRadian = mapSize.tileSize / (2 * Math.PI);
-
-  const lng = (pointShifted.x - pointOrigin.x) / pixelsPerLonDegree;
-  const latRadians = (pointShifted.y - pointOrigin.y) / -pixelsPerLonRadian;
+  const lng = xOffset / pixelsPerLonDegree;
+  const latRadians = yOffset / -pixelsPerLonRadian;
   const lat = radiansToDegrees(2 * Math.atan(Math.exp(latRadians)) - Math.PI / 2);
 
   return [lng, lat];
-- 
GitLab