diff --git a/src/store/actions.js b/src/store/actions.js index 87d68e8..b719aa6 100644 --- a/src/store/actions.js +++ b/src/store/actions.js @@ -122,7 +122,8 @@ const getLastLocations = async ({ commit, state }) => { commit(types.SET_LAST_LOCATIONS, lastLocations); }; -const _getTravelStats = (locationHistory) => { +// Export for testing purposes only +export const _getTravelStats = (locationHistory) => { const start = Date.now(); let distanceTravelled = 0; let elevationGain = 0; @@ -130,16 +131,21 @@ const _getTravelStats = (locationHistory) => { Object.keys(locationHistory).forEach((user) => { Object.keys(locationHistory[user]).forEach((device) => { let lastLatLng = null; + let lastAlt = null; locationHistory[user][device].forEach((location) => { if ( config.filters.minAccuracy !== null && location.acc > config.filters.minAccuracy ) return; - const latLng = L.latLng(location.lat, location.lon, location.alt ?? 0); + const latLng = L.latLng(location.lat, location.lon, location.alt); if (lastLatLng !== null) { const distance = distanceBetweenCoordinates(lastLatLng, latLng); - const elevationChange = latLng.alt - lastLatLng.alt; + // calculate the elevationChange only if there is an alt available + let elevationChange = 0; + if (lastAlt !== null && latLng.alt !== undefined) { + elevationChange = latLng.alt - lastAlt; + } if ( typeof config.map.maxPointDistance === "number" && config.map.maxPointDistance > 0 @@ -153,6 +159,9 @@ const _getTravelStats = (locationHistory) => { else elevationLoss += -elevationChange; } } + if (latLng.alt !== undefined) { + lastAlt = latLng.alt; + } lastLatLng = latLng; }); }); diff --git a/tests/actions.test.js b/tests/actions.test.js new file mode 100644 index 0000000..edd8656 --- /dev/null +++ b/tests/actions.test.js @@ -0,0 +1,31 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { _getTravelStats } from "@/store/actions"; + +import { L } from "leaflet"; + +describe("_getTravelStats", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("calculates total distance and elevation with and without alt", () => { + const testData = { + user1: { + device1: [ + { lat: 52.214908, lon: 8.116938, alt: 100, acc: 5 }, + { lat: 52.214908, lon: 8.116938, alt: 105, acc: 5 }, + { lat: 52.220619, lon: 8.104137, /* no alt */ acc: 5 }, + { lat: 52.220619, lon: 8.104137, alt: 95, acc: 5 }, + { lat: 52.227348, lon: 8.094349, /* no alt */ acc: 5 }, + ], + }, + }; + + const stats = _getTravelStats(testData); + + expect(stats.distanceTravelled).toBeCloseTo(2080.9568); + expect(stats.elevationGain).toBe(5); + expect(stats.elevationLoss).toBe(10); + }); + +});