Skip to content

Commit

Permalink
fix: correct average per session visualization
Browse files Browse the repository at this point in the history
  • Loading branch information
thraizz committed May 29, 2024
1 parent 12b9c80 commit c4d6094
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 38 deletions.
101 changes: 64 additions & 37 deletions src/components/panels/AveragesPerSession.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import { useContext, useMemo, useState } from "react";
import { PlainObject, Vega, VisualizationSpec } from "react-vega";
import { Vega, VisualizationSpec } from "react-vega";
import { useClubsPerSession } from "../../hooks/useClubsPerSesssion";
import { SessionContext } from "../../provider/SessionContext";
import { GolfSwingData } from "../../types/GolfSwingData";
import { useAveragedSwings } from "../../utils/calculateAverages";
import { getAllDataFromSession } from "../../utils/getAllDataFromSession";
import {
AveragedSwing,
useAveragePerSession,
} from "../../utils/calculateAverages";
import { BaseLabel } from "../base/BaseLabel";
import { BaseListbox } from "../base/BaseListbox";

export const AveragesPerSession = () => {
const { sessions } = useContext(SessionContext);

const [yField, setYField] = useState("Smash Factor");
const [yField, setYField] = useState<keyof AveragedSwing>("Smash Factor");
const [club, setClub] = useState<string | null>(null);

const fields = useMemo(() => {
Expand All @@ -27,7 +28,7 @@ export const AveragesPerSession = () => {
const spec: VisualizationSpec = {
$schema: "https://vega.github.io/schema/vega-lite/v5.json",
data: { name: "table" },
mark: "bar",
mark: "line",
encoding: {
x: {
axis: {
Expand All @@ -45,45 +46,54 @@ export const AveragesPerSession = () => {
},
};

const averages = useAveragedSwings();
const averages = useAveragePerSession();

const clubDataByDate: {
[key: string]: GolfSwingData[];
} = useMemo(() => {
if (averages) {
return averages.reduce(
(acc, curr) => {
if (curr["name"] === club) {
if (!acc[curr["Date"]]) {
acc[curr["Date"]] = [];
}
acc[curr["Date"]].push(curr);
}
return acc;
},
{} as { [key: string]: GolfSwingData[] },
);
}
return {};
}, [averages, club]);
const clubDataByDate = useMemo(() => {
if (!averages) return {};

return averages.reduce(
(accumulatedData, currentSwing) => {
const clubData = currentSwing.averages.find(
(swing) => swing.name === club,
);
if (clubData) {
accumulatedData[currentSwing.date] =
clubData[yField as keyof AveragedSwing];
}
return accumulatedData;
},
{} as { [key: string]: YFieldValue },
);
}, [averages, yField, club]);

const clubSelected = club && club !== "All";
const averagesByDate: PlainObject = useMemo(() => {
type ClubDataForTable = {
table: {
x: string | null;
y: YFieldValue;
}[];
};

const averagesByDate: ClubDataForTable = useMemo(() => {
if (sessions) {
if (clubSelected) {
if (clubSelected && clubDataByDate) {
return {
table: clubDataByDate,
table: Object.entries(clubDataByDate)?.map((x) => ({
x: x[0],
y: x[1],
})),
};
} else {
return {
table: averages.map((x) => ({
x: x.date,
y: getAllAveragesByField(x.averages, yField),
})),
};
}
return {
table: getAllDataFromSession(sessions).map((row) => ({
x: row["Date"] || row["Datum"],
y: row[yField as keyof GolfSwingData],
})),
};
}
return { table: [] };
}, [sessions, yField, clubDataByDate, clubSelected]);
}, [sessions, clubSelected, clubDataByDate, averages, yField]);

const clubs = useClubsPerSession();

Expand All @@ -98,7 +108,7 @@ export const AveragesPerSession = () => {
<div className="flex flex-col gap-4 md:flex-row">
<BaseListbox
options={fields}
setOption={setYField}
setOption={setYField as (option: string) => void}
value={yField}
valueText={yField as string}
/>
Expand Down Expand Up @@ -131,3 +141,20 @@ export const AveragesPerSession = () => {
</div>
);
};
const getAllAveragesByField = (
averages: AveragedSwing[],
yField: keyof AveragedSwing,
): YFieldValue => {
// @ts-expect-error - TODO Fix typing here
return averages.reduce((acc, current) => {
if (current[yField] === undefined) {
return acc;
}
if (acc === null) {
return current[yField];
}
return acc + current[yField];
}, null);
};

type YFieldValue = string | number | null | undefined;
21 changes: 20 additions & 1 deletion src/utils/calculateAverages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useContext, useMemo } from "react";
import { SessionContext } from "../provider/SessionContext";
import { SettingsContext } from "../provider/SettingsContext";
import { GolfSwingData } from "../types/GolfSwingData";
import { Sessions } from "../types/Sessions";
import type { Sessions } from "../types/Sessions";
import { translateSwingsToEnglish } from "./csvLocalization";

const quantile = (arr: number[], q: number) => {
Expand Down Expand Up @@ -39,6 +39,25 @@ export const useAveragedSwings = () => {
}, [sessions, settings.useIQR, settings.useAboveAverageShots]);
};

export type AveragedSwingRecord = {
date: string;
averages: AveragedSwing[];
};
export const useAveragePerSession = () => {
const { sessions } = useContext(SessionContext);

return useMemo(() => {
if (sessions) {
return Object.values(sessions).reduce((previousValue, currentValue) => {
const date = currentValue.date;
const averages = calculateAverages({ "1": currentValue });
return [...previousValue, { date, averages }];
}, [] as AveragedSwingRecord[]);
}
return [];
}, [sessions]);
};

// Calculate averages for each club across all sessions
export const calculateAverages: (
input: Sessions,
Expand Down

0 comments on commit c4d6094

Please sign in to comment.