Advertisement
sandervspl

cars.json mod script

Apr 10th, 2024
665
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { getCachedData, saveCachedData } from "./cache.js";
  2. import { Address, CarWithCoordinates } from "./types.js";
  3.  
  4. const cars: CarWithCoordinates[] = getCachedData("cars");
  5.  
  6. type Cache = Record<string, { lat: number; lon: number }>;
  7.  
  8. function updateOwnershipCoordinates(cars: CarWithCoordinates[]): void {
  9.   const addressCache: Cache = {};
  10.  
  11.   // Build a cache from available coordinates in any car_ownership
  12.   for (const car of cars) {
  13.     for (const ownership of car.car_ownership) {
  14.       if (
  15.         ownership.address &&
  16.         ownership.address.lat !== undefined &&
  17.         ownership.address.lon !== undefined
  18.       ) {
  19.         const addressKey = getAddressKey(ownership.address);
  20.         if (addressKey == null) {
  21.           console.log("no key found for", ownership.address);
  22.           continue;
  23.         }
  24.         addressCache[addressKey] = {
  25.           lat: ownership.address.lat,
  26.           lon: ownership.address.lon,
  27.         };
  28.       }
  29.     }
  30.   }
  31.  
  32.   // Use the cache to populate missing coordinates in car_ownership
  33.   for (const car of cars) {
  34.     for (const ownership of car.car_ownership) {
  35.       if (
  36.         ownership.address &&
  37.         (ownership.address.lat === undefined ||
  38.           ownership.address.lon === undefined)
  39.       ) {
  40.         const addressKey = getAddressKey(ownership.address);
  41.         if (addressKey == null) {
  42.           console.log("no key found for", ownership.address);
  43.           continue;
  44.         }
  45.         const cachedCoords = addressCache[addressKey];
  46.         if (cachedCoords) {
  47.           ownership.address.lat = cachedCoords.lat;
  48.           ownership.address.lon = cachedCoords.lon;
  49.         }
  50.       }
  51.     }
  52.   }
  53. }
  54.  
  55. function getAddressKey(address: Address) {
  56.   // Create a unique key for each address based on its distinguishable properties
  57.   return address.postal_code?.replaceAll(" ", "");
  58. }
  59.  
  60. // Overwrite cars.json with new data
  61. updateOwnershipCoordinates(cars);
  62.  
  63. saveCachedData("cars", cars);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement