Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { getCachedData, saveCachedData } from "./cache.js";
- import { Address, CarWithCoordinates } from "./types.js";
- const cars: CarWithCoordinates[] = getCachedData("cars");
- type Cache = Record<string, { lat: number; lon: number }>;
- function updateOwnershipCoordinates(cars: CarWithCoordinates[]): void {
- const addressCache: Cache = {};
- // Build a cache from available coordinates in any car_ownership
- for (const car of cars) {
- for (const ownership of car.car_ownership) {
- if (
- ownership.address &&
- ownership.address.lat !== undefined &&
- ownership.address.lon !== undefined
- ) {
- const addressKey = getAddressKey(ownership.address);
- if (addressKey == null) {
- console.log("no key found for", ownership.address);
- continue;
- }
- addressCache[addressKey] = {
- lat: ownership.address.lat,
- lon: ownership.address.lon,
- };
- }
- }
- }
- // Use the cache to populate missing coordinates in car_ownership
- for (const car of cars) {
- for (const ownership of car.car_ownership) {
- if (
- ownership.address &&
- (ownership.address.lat === undefined ||
- ownership.address.lon === undefined)
- ) {
- const addressKey = getAddressKey(ownership.address);
- if (addressKey == null) {
- console.log("no key found for", ownership.address);
- continue;
- }
- const cachedCoords = addressCache[addressKey];
- if (cachedCoords) {
- ownership.address.lat = cachedCoords.lat;
- ownership.address.lon = cachedCoords.lon;
- }
- }
- }
- }
- }
- function getAddressKey(address: Address) {
- // Create a unique key for each address based on its distinguishable properties
- return address.postal_code?.replaceAll(" ", "");
- }
- // Overwrite cars.json with new data
- updateOwnershipCoordinates(cars);
- saveCachedData("cars", cars);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement